React.js - 如何在卸载组件和安装另一个组件时添加动画?

时间:2017-09-05 20:28:35

标签: javascript reactjs virtual-dom

我有这个代码用于卸载和重新安装元素:

import React, { Component } from 'react';
import './App.css';
import Header from './Header';
import Bottom1 from './Bottom1';
import Bottom2 from './Bottom2';
class App extends Component {
  constructor(){
    super();
    this.state={
      playWindow: true
     }
     this.update = this.update.bind(this);
  }

  update(){
    const newState = this.state.playWindow? false : true;
    this.setState({playWindow: newState});
  }

  render() {
    return (
      <div className="App">
        <Header update={this.update}/>
        {this.state.playWindow?  <Bottom1/>  : <Bottom2/> }
      </div>
    );
  }
}

export default App;

当我执行操作时,会交换组件。问题是没有过渡,切换的情况很糟糕。如何添加一个动画,比如一个淡出,然后另一个淡入?

1 个答案:

答案 0 :(得分:1)

您可以使用react-transition-group为组件制作动画。查看文档here

来自官方文档的示例:

class TodoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {items: ['hello', 'world', 'click', 'me']};
    this.handleAdd = this.handleAdd.bind(this);
  }

  handleAdd() {
    const newItems = this.state.items.concat([
      prompt('Enter some text')
    ]);
    this.setState({items: newItems});
  }

  handleRemove(i) {
    let newItems = this.state.items.slice();
    newItems.splice(i, 1);
    this.setState({items: newItems});
  }

  render() {
    const items = this.state.items.map((item, i) => (
      <div key={item} onClick={() => this.handleRemove(i)}>
        {item}
      </div>
    ));

    return (
      <div>
        <button onClick={this.handleAdd}>Add Item</button>
        <ReactCSSTransitionGroup
          transitionName="example"
          transitionEnterTimeout={500}
          transitionLeaveTimeout={300}>
          {items}
        </ReactCSSTransitionGroup>
      </div>
    );
  }
}