【问题标题】:React.js -- How to add an animation when unmounting a component and mounting another?React.js -- 如何在卸载组件和安装另一个组件时添加动画?
【发布时间】:2018-02-14 05:12:47
【问题描述】:
我有这个用于卸载和重新安装元素的代码:
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;
当我执行操作时,组件会被交换。问题是没有过渡,切换很粗糙。如何添加动画,比如一个淡出,另一个淡入?
【问题讨论】:
标签:
javascript
reactjs
virtual-dom
【解决方案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>
);
}
}