【问题标题】:React: How to animate the change of the component rendered?React:如何动画化渲染组件的变化?
【发布时间】:2017-05-19 06:32:10
【问题描述】:

我更改了通过时间间隔呈现的组件。

我希望能够在每次发生更改时添加动画。最好的方法是什么?

constructor (props) {
    super(props)
    this.state = { currentComponent: 1,
    numberOfComponents: 2}
}

componentWillMount() {
    setInterval(() => {
       if(this.state.currentComponent === 2) {
           this.setState({currentComponent: 1})
       } else {
           this.setState({currentComponent: this.state.currentComponent + 1})
       }
    }, 5000)
}

render(){

    let currentComponent = null;

    if(this.state.currentComponent === 1) {
        currentComponent = <ComponentOne/>;

    } else {
        currentComponent = <ComponentTwo/>;
    }

    return(
        currentComponent
    )
}

编辑:

当尝试使用“react-addons-css-transition-group”时 我收到以下错误:

【问题讨论】:

  • 我认为最简单的方法是使用 CSS3 过渡。你根据你的状态给你的元素一个类,这会改变你元素的样式。您可以使用 CSS3 转换(或 CSS3 动画)转换此样式。

标签: javascript css reactjs animation


【解决方案1】:

您可以像 section 中提供的那样使用 ReactCSSTransitionGroup

你的 CSS:

.example-enter {
  opacity: 0.01;
}

.example-enter.example-enter-active {
  opacity: 1;
  transition: opacity 500ms ease-in;
}

.example-leave {
  opacity: 1;
}

.example-leave.example-leave-active {
  opacity: 0.01;
  transition: opacity 300ms ease-in;
}

看起来像这样:

import ReactCSSTransitionGroup from 'react-addons-css-transition-group';



class MyComponent extends Component {
  constructor (props) {
    super(props)
    this.state = { currentComponent: 1,
    numberOfComponents: 2}
  }

  componentWillMount() {
    setInterval(() => {
       if(this.state.currentComponent === 2) {
           this.setState({currentComponent: 1})
       } else {
           this.setState({currentComponent: this.state.currentComponent + 1})
       }
    }, 5000)
  }

  render(){

    let currentComponent = null;

    if(this.state.currentComponent === 1) {
        currentComponent = <ComponentOne/>;

    } else {
        currentComponent = <ComponentTwo/>;
    }

    return(
        <ReactCSSTransitionGroup
          transitionName="example"
           transitionEnterTimeout={500}
          transitionLeaveTimeout={300}>
          {currentComponent}
        </ReactCSSTransitionGroup>

    )
  }
}

【讨论】:

  • 谢谢。这就是我尝试过的,但每次我导入那个库时。我不断收到以下错误:Uncaught TypeError: React.PropTypes.shape is not a function
  • 这个错误可能在其他地方......你的应用程序中哪里有 Protypes 定义?
  • 我实际上是从图书馆得到的。我在帖子中添加了错误截图。
  • 你使用的是哪个版本的 react 和 react-transitions?
  • react@15.4.1 react-addons-css-transition-group@15.0.2
猜你喜欢
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 2017-01-02
  • 2015-05-02
  • 2021-09-20
  • 2018-07-01
  • 2022-01-25
相关资源
最近更新 更多