Easing out transition in React

时间:2015-10-30 22:12:51

标签: css reactjs

I'm just starting with React and running into an issue with something I was expecting to be quite simple. All I'm trying to do is have a block of text fade in and then fade out based on a simple trigger, but I can't get it to fade out.

The code is below and I've got a button that makes the message appear. It is fading in fine and disappearing after two seconds, but I was expecting the message to fade out upon leaving... but clearly I'm misunderstanding the meaning of that in the React-ish transition CSS.

Here is the React component:

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>;
  }
}

Here is the 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;
}

2 个答案:

答案 0 :(得分:1)

您应该使用ReactCSSTransitionGroup,即ReactTransitionGroup

周围的高级API
import `ReactCSSTransitionGroup` from "react-addons-css-transition-group";

在React > v0.14中,如果您启用了transitionEnterTimeout,那么您还必须将transitionLeaveTimeout transitionAppearTimeout和可选的transitionAppear道具传递给该组件

最后,您需要将key - 属性传递给您的动画儿童

  

您必须为ReactCSSTransitionGroup的所有子项提供键属性,即使只渲染单个项目也是如此。这就是React将如何确定哪些孩子已进入,离开或留下。

您可能还需要对代码进行一些重构,以使ReactCSSTransitionGroup不在<AnimatedText >内,而是包裹在{sent_element}

有关详细信息,请参阅React/Animation-docs

答案 1 :(得分:0)

要获得更多动画乐趣,请参阅GitHub上提供的react-motion lib https://github.com/chenglou/react-motion