Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a dynamic pop-up window component in React

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

本文小编为大家详细介绍"React中如何实现一个动效弹窗组件",内容详细,步骤清晰,细节处理妥当,希望这篇"React中如何实现一个动效弹窗组件"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1. 没有动效的弹窗

在 React 中,可以这样来实现:

interface ModalProps { open: boolean; onClose?: () => void; children?: any;}const Modal = ({open. onClose, children}: ModalProps) => { if (!open) { return null; } return createPortal( {children} setOpen(true)}>show modal setOpen(false)}> modal content );};2. 自己动手实现有动效的弹窗

很多同学在自己实现动效时,经常是展示的时候有动效,关闭的时候没有动效。都是动效的时机没有控制好。这里我们先自己来实现一下动效的流转。

刚开始我实现的时候,动效只有开始状态和结束状态,需要很多的变量和逻辑来控制这个动效。

后来我参考了react-transition-group组件的实现,他是将动效拆分成了几个部分,每个部分分别进行控制。

展开动效的顺序:enter -> enter-active -> enter-done;

关闭动效的顺序:exit -> exit-active -> exit-done;

动效过程在enter-active和exit-active的过程中。

我们再通过一个变量 active 来控制是关闭动效是否已执行关闭,参数 open 只控制是执行展开动效还是关闭动效。

当 open 和 active 都为 false 时,才销毁弹窗。

const Modal = ({ open, children, onClose }) => { const [active, setActive] = useState(false); // 弹窗的存在周期 if (!open && !active) { return null; } return ReactDOM.createPortal( {children} {children} setOpen(true)}>show modal setOpen(false)}> modal content );};

3. react-transition-group

我们在实现动效的思路上借鉴了 react-transition-group 中的CSSTransition组件。CSSTransition已经帮我封装好了动效展开和关闭的过程,我们在实现弹窗时,可以直接使用该组件。

这里有一个重要的属性:unmountOnExit,表示在动效结束后,卸载该组件。

const Modal = ({ open, onClose }) => { // http://reactcommunity.org/react-transition-group/css-transition/ // in属性为true/false,true为展开动效,false为关闭动效 return createPortal( {children}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report