我刚刚开始使用React并遇到一些我期待非常简单的问题.我所要做的就是让一段文字淡入,然后根据一个简单的触发器淡出,但我无法让它淡出.
代码在下面,我有一个按钮,使消息出现.两秒钟后,它正在逐渐消失,但是我希望消息在离开时消失……但显然我在React-ish转换CSS中误解了它的含义.
这是React组件:
class MessageSender extends React.Component {
render() {
let sent_element = null;
if (this.state.linkSent) {
sent_element = <AnimatedText/>;
}
return (
<div>
{sent_element}
</div>
);
//A fetch then triggers:
...then((json) => {
if (json.success) {
_this.setState({
linkSent: true
})
setTimeout(
function(){
_this.setState({linkSent:false});
},2000
)
}
});
}
class AnimatedText extends React.Component {
render() {
return <ReactTransitionGroup transitionAppear={true} transitionName="fadeInOut">
<div>Sent!</div>
</ReactTransitionGroup>;
}
}
这是CSS:
.fadeInOut-appear {
opacity: 0.01;
transition: opacity 0.4s ease-in-out;
-webkit-transition: opacity 0.4s ease-in-out;
}
.fadeInOut-appear.fadeInOut-appear-active {
opacity: 1;
}
.fadeInOut-leave {
opacity: 1;
transition: opacity 0.4s ease-in-out;
-webkit-transition: opacity 0.4s ease-in-out;
}
.fadeInOut-leave.fadeInOut-leave-active {
opacity: 0.01;
}
最佳答案 您应该使用ReactCSSTransitionGroup,这是ReactTransitionGroup周围的高级API
import `ReactCSSTransitionGroup` from "react-addons-css-transition-group";
在React中> v0.14,如果你启用了transitionAppear,你还必须将transitionEnterTimeout transitionLeaveTimeout和可选的transitionAppearTimeout props传递给组件(你可以这样做).
最后,您需要将key-attribute传递给动画孩子
You must provide the key attribute for all children of ReactCSSTransitionGroup, even when only rendering a single item. This is how React will determine which children have entered, left, or stayed.
您可能还需要重构一下代码,以便您的ReactCSSTransitionGroup不在< AnimatedText>内,而是包裹在您的{sent_element}中
有关更多信息,请参见React/Animation-docs.