我正在使用React,并尝试使用React-transition- Fade创建一个React-transition-group组件,以根据状态中存储的条件淡入和淡出元素:http://reactcommunity.org/react-transition-group/css-transition/
这就是我现在所拥有的:
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;
}当组件被安装时,使用.5s时,不透明度从0过渡到1。但是当它被卸载时,它不是动画的:组件消失而没有过渡。
我用这个组件做了一个沙箱来测试它:https://codesandbox.io/s/k027m33y23我确信这是一种常见的情况,但我找不到一种方法在卸载时对该组件进行动画处理。如果有任何人有任何想法,我们将非常欢迎!
-- EDIT --正如@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>该组件将根据CSSTransition组件中的in属性自动挂载或卸载。下面是codesandbox中的最后一段代码:https://codesandbox.io/s/62m86nm7qw
发布于 2018-08-09 23:32:09
这是意料之中的,因为当状态改变时,动画还没有开始,但是孩子已经走了。
所以它就像是神奇的瞬间消失。好吧,我们只需要隐藏它,对吗?删除条件渲染。
我检查过,动画完成后,节点会自动移除。所以不需要使用条件渲染。幸运的是!代码变成:
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 = {
logoIntro: true,
mounted: false
};
}
componentDidMount() {
this.setState({
mounted: true
});
}
render() {
return (
<div className="root">
<CSSTransition
in={this.state.mounted}
appear={true}
unmountOnExit
classNames="fade"
timeout={1000}
>
<div>
<button
onClick={() => {
this.setState({
mounted: !this.state.mounted
});
}}
>
Remove
</button>
<div>SOME COMPONENT</div>
</div>
</CSSTransition>
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById("root"));https://stackoverflow.com/questions/51770658
复制相似问题