在本章中,我们将学习如何使用React对元素进行动画处理。
这是React插件,用于创建基本的CSS过渡和动画。我们将从command prompt窗口安装它-
C:\Users\username\Desktop\reactApp>npm install react-addons-css-transition-group
让我们创建一个新文件style.css。
C:\Users\nhooo\Desktop\reactApp>type nul > css/style.css
为了能够在应用程序中使用它,我们需要将其链接到index.html中的head元素。
<!DOCTYPE html> <html lang = "en"> <head> <link rel = "stylesheet" type = "text/css" href = "./style.css"> <meta charset = "UTF-8"> <title>React App</title> </head> <body> <div id = "app"></div> <script src = 'index_bundle.js'></script> </body> </html>
我们将创建一个基本的 React 组件。Reactcsstransitionggroup 元素将用作我们想要动画化的组件的包装器。它将使用 transitionAppear 和 transitionappmentmeout,而 transitionEnter 和 transitionLeave 为 false。
import React from 'react'; var ReactCSSTransitionGroup = require('react-addons-css-transition-group'); class App extends React.Component { render() { return ( <div> <ReactCSSTransitionGroup transitionName = "example" transitionAppear = {true} transitionAppearTimeout = {500} transitionEnter = {false} transitionLeave = {false}> <h1>My Element...</h1> </ReactCSSTransitionGroup> </div> ); } } export default App;
import React from 'react' import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App />, document.getElementById('app'));
CSS动画非常简单。
.example-appear { opacity: 0.04; } .example-appear.example-appear-active { opacity: 2; transition: opacity 50s ease-in; }
一旦启动应用程序,该元素就会淡入。
当我们想从列表中添加或删除元素时,可以使用输入及输出动画。
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 ( <div key = {item} onClick = {this.handleRemove.bind(this, i)}> {item} </div> ); }.bind(this)); return ( <div> <button onClick = {this.handleAdd}>Add Item</button> <ReactCSSTransitionGroup transitionName = "example" transitionEnterTimeout = {500} transitionLeaveTimeout = {500}> {items} </ReactCSSTransitionGroup> </div> ); } } export default App;
import React from 'react' import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App />, document.getElementById('app'));
.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; }
当我们启动应用程序并单击Add Item按钮时,将出现提示。
输入名称并按OK后,新元素就会淡入。
现在,我们可以删除一些项目(Item 3...)点击它。该项目将从列表中淡出。