React动画库:react-transition-group官方文档地址
官方介绍
There are 4 main states a Transition can be in:
‘entering’
‘entered’
‘exiting’
‘exited’
Transition state is toggled via the in prop. When true the component begins the “Enter” stage. During this stage, the component will shift from its current transition state, to ‘entering’ for the duration of the transition and then to the ‘entered’ stage once it’s complete. Let’s take the following example (we’ll use the useState hook):
(大致翻译就是有四种改变的state,这个state通过prop进行改变,然后就是我下面说的几种改变的方式)
import React, { useState } from "react";
import { Transition } from "react-transition-group";
import { useRef } from "react";
const duration = 300;
const defaultStyle = {
transition: `opacity ${duration}ms ease-in-out`,
opacity: 0,
color: "red",
};
const transitionStyles = {
entering: { opacity: 1 },
entered: { opacity: 1, color: "yellow" },
exiting: { opacity: 0 },
exited: { opacity: 0 },
};
export default function Transition1() {
const [inProp, setInProp] = useState(false);
const nodeRef = useRef(null);
return (
<div>
{/* state四个状态 entering entered exiting exited */}
{/* in控制控制组件的状态值(state),当in改变的时候state也会有相应的改变,timeout设置动画时间 */}
{/* 当in为true-->false时entered,exiting,当timeout结束之后exited */}
{/* 当in为false-->true时entered,exiting,当timeout结束之后exited */}
<Transition nodeRef={nodeRef} in={inProp} timeout={500}>
{(state) => {
console.log(state);
return (
<div
ref={nodeRef}
style={{
// 设置的默认样式
...defaultStyle,
// 改变state用transitionStyles覆盖掉默认的样式,因为state再改变所以样式也在改变
...transitionStyles[state],
}}
>
I'm a fade Transition!
</div>
);
}}
</Transition>
<button onClick={() => setInProp(!inProp)}>Click to Enter</button>
</div>
);
}