我正在使用 React,我正在尝试Fade
使用 React-transition-group 创建一个组件,以根据状态中存储的条件淡入和淡出元素:http ://reactcommunity.org/react-transition-组/css-过渡/
这就是我现在所拥有的:
import React from "react";
import ReactDOM from "react-dom";
import { CSSTransition } from "react-transition-group";
import "./styles.css";
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
mounted: false
};
}
componentDidMount() {
setTimeout(() => {
this.setState({
mounted: true
});
}, 10);
}
render() {
return (
<div className="root">
<CSSTransition
in={this.state.mounted}
appear={true}
unmountOnExit
classNames="fade"
timeout={1000}
>
{this.state.mounted ? (
<div>
<button
onClick={() => {
this.setState({
mounted: !this.state.mounted
});
}}
>
Remove
</button>
<div>COMPONENT</div>
</div>
) : (
<div />
)}
</CSSTransition>
</div>
);
}
}
这是CSS
.fade-enter {
opacity: 0;
transition: opacity .5s ease;
}
.fade-enter-active {
opacity: 1;
transition: opacity .5s ease;
}
.fade-exit {
opacity: 1;
transition: opacity .5s ease;
}
.fade-exit-active {
opacity: 0;
transition: opacity .5s ease;
}
安装组件后,不透明度会在 0.5 秒内从 0 过渡到 1。但是当它卸载时,它没有动画:组件在没有过渡的情况下消失。
我用这个组件制作了一个沙箱来测试它:https ://codesandbox.io/s/k027m33y23 我确信这是一种常见的情况,但我找不到在卸载时为组件设置动画的方法。如果有人有任何想法,将非常欢迎!
-- 编辑 -- 正如@IPutuYogaPermana 所说,CSSTransition 中的条件渲染不是必需的。所以这:
{this.state.mounted ? (
<div>
<button
onClick={() => {
this.setState({
mounted: !this.state.mounted
});
}}
>
Remove
</button>
<div>COMPONENT</div>
</div>
) : (
<div />
)}
应该是这样的:
<div>
<button
onClick={() => {
this.setState({
mounted: !this.state.mounted
});
}}
>
Remove
</button>
<div>COMPONENT</div>
</div>
该组件将根据in
CSSTransition 组件中的属性自动挂载或卸载。这里是codesandbox中的最终代码:https ://codesandbox.io/s/62m86nm7qw