如何在React中使用CSS3动画
一、需求
1.在页面添加item时要有渐变效果
2.单击item可删除,带渐变效果
二、代码
1.通过Reacat插件ReactCSSTransitionGroup实现
1 <!DOCTYPE html> 2 <html lang="zh-cn"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>React动画</title> 6 <style> 7 .example-enter { 8 opacity: 0.01; 9 transition: opacity .5s ease-in; 10 } 11 12 .example-enter.example-enter-active { 13 opacity: 1; 14 } 15 16 .example-leave { 17 opacity: 1; 18 transition: opacity .5s ease-in; 19 } 20 21 .example-leave.example-leave-active { 22 opacity: 0.01; 23 } 24 </style> 25 </head> 26 <body> 27 <script src="./react-0.13.2/build/react-with-addons.js"></script> 28 <script src="./react-0.13.2/build/JSXTransformer.js"></script> 29 <script type="text/jsx"> 30 var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; 31 32 var TodoList = React.createClass({ 33 getInitialState: function() { 34 return {items: ['hello', 'world', 'click', 'me']}; 35 }, 36 handleAdd: function() { 37 var newItems = 38 this.state.items.concat([prompt('Enter some text')]); 39 this.setState({items: newItems}); 40 }, 41 handleRemove: function(i) { 42 var newItems = this.state.items; 43 newItems.splice(i, 1); 44 this.setState({items: newItems}); 45 }, 46 render: function() { 47 var items = this.state.items.map(function(item, i) { 48 return ( 49 <div key={item} onClick={this.handleRemove.bind(this, i)}> 50 {item} 51 </div> 52 ); 53 }.bind(this)); 54 return ( 55 <div> 56 <button onClick={this.handleAdd}>Add Item</button> 57 <ReactCSSTransitionGroup transitionName="example"> 58 {items} 59 </ReactCSSTransitionGroup> 60 </div> 61 ); 62 } 63 }); 64 React.render(<TodoList></TodoList>, document.body); 65 </script> 66 </body> 67 </html>
三、运行结果
You can do anything you set your mind to, man!