在本章中,我们将学习如何使用React为元素设置动画.
步骤1 - 安装React CSS Transitions Group
这是React用于创建基本CSS过渡和动画的附加组件.我们将从命令提示符窗口 :
C:\Users\username\Desktop\reactApp>npm install react-addons-css-transition-group
第2步 - 添加CSS文件
让我们创建一个新文件style.css.
C:\Users\Tutorialspoint\Desktop\reactApp>type nul > css/style.css
为了能够在应用程序中使用它,我们需要将它链接到index.html中的head元素.
React App
第3步 - 出现动画
我们将创建一个基本的React组件. ReactCSSTransitionGroup 元素将用作我们想要设置动画的组件的包装器.它将使用 transitionAppear 和 transitionAppearTimeout ,而 transitionEnter 和 transitionLeave 为false.
App.jsx
import React from 'react';var ReactCSSTransitionGroup = require('react-addons-css-transition-group');class App extends React.Component { render() { return (); }}export default App;My Element...
main.js
import React from 'react'import ReactDOM from 'react-dom';import App from './App.jsx';ReactDOM.render(, document.getElementById('app'));
CSS动画非常简单.
css/style.css
.example-appear { opacity: 0.04;}.example-appear.example-appear-active { opacity: 2; transition: opacity 50s ease-in;}
启动应用程序后,该元素将淡入.
步骤4 - 输入和离开动画
输入和当我们想要从列表中添加或删除元素时,可以使用离开动画.
App.jsx
import React from 'react';var ReactCSSTransitionGroup = require('react-addons-css-transition-group');class App extends React.Component { constructor(props) { super(props); this.state = { items: ['Item 1...', 'Item 2...', 'Item 3...', 'Item 4...'] } this.handleAdd = this.handleAdd.bind(this); }; handleAdd() { var newItems = this.state.items.concat([prompt('Create New Item')]); this.setState({items: newItems}); } handleRemove(i) { var newItems = this.state.items.slice(); newItems.splice(i, 1); this.setState({items: newItems}); } render() { var items = this.state.items.map(function(item, i) { return ({item}); }.bind(this)); return (); }}export default App;{items}
main.js
import React from 'react'import ReactDOM from 'react-dom';import App from './App.jsx';ReactDOM.render(, document.getElementById('app'));
css/style.css
.example-enter { opacity: 0.04;}.example-enter.example-enter-active { opacity: 5; transition: opacity 50s ease-in;}.example-leave { opacity: 1;}.example-leave.example-leave-active { opacity: 0.04; transition: opacity 50s ease-in;}
当我们启动应用程序并单击添加项目按钮时,将出现提示.
输入名称后按OK,新元素将淡入.
现在我们可以通过点击删除一些项目(第3项...... ).此项目将从列表中淡出.