一、安装依赖:react-transition-group
reactcommunity.org/react-trans…
npm install react-transition-group
二、过渡动画实现示例
jsx
import { CSSTransition } from 'react-transition-group';
import React, { useRef } from 'react';
import './index.css';
function Transition1() {
const [show, setShow] = React.useState(true);
const timeout = 3000
const nodeRef = useRef(null);
return (
<div>
<h2>过渡动画</h2>
<div className="btn-group" style={{ display: 'flex', gap: '10px', justifyContent: 'center', cursor: 'pointer' }}>
<p onClick={() => setShow(true)} style={show ? { color: 'red' } : {}}>显示</p>
<p onClick={() => setShow(false)} style={!show ? { color: 'red' } : {}}>隐藏</p>
</div>
{/*
1、nodeRef方式使用CSSTransition:
- 通过nodeRef属性传入ref对象,来避免findDOMNode的使用,从而避免在严格模式下出现警告。
- 需要注意的是,使用nodeRef时,必须确保ref对象正确地引用了要应用过渡效果的DOM节点。
- 另外,nodeRef方式不支持某些过渡效果,如appear效果。
*/}
{/*
2、classNames、in、timeout
- classNames 属性指定了过渡效果的类名前缀,这些类名会在不同的过渡阶段自动添加到元素上,从而实现动画效果。
- 通过 in 属性控制过渡效果的触发,当 in 为 true 时,元素进入过渡状态;当 in 为 false 时,元素离开过渡状态。
- timeout 属性指定了过渡效果的持续时间,单位为毫秒。
*/}
<CSSTransition nodeRef={nodeRef} classNames="div-box" in={show} timeout={timeout}>
<div ref={nodeRef} className="div-box">
<h3>内容</h3>
</div>
</CSSTransition>
</div>
);
}
export default Transition1;
css
.div-box {
transition: opacity 3s;
}
.div-box-enter {
display: block;
opacity: 0;
}
.div-box-enter-active {
display: block;
opacity: 0.5;
}
.div-box-enter-done {
display: block;
opacity: 1;
}
.div-box-exit {
display: block;
opacity: 1;
}
.div-box-exit-active {
display: block;
opacity: 0.5;
}
.div-box-exit-done {
display: none;
opacity: 0;
}