React属性的3种设置方式
一、
不推荐用setProps,因为以React的设计思想相悖,推荐以父组件向子组件传递属性的方式
二、3种用法的代码
1.键值对
1 <!DOCTYPE html> 2 <html lang="zh-cn"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Hello, World</title> 6 </head> 7 <body> 8 <script src="./react-0.13.2/react-0.13.2/build/react.js"></script> 9 <script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script> 10 <script type="text/jsx"> 11 var style = { 12 color: "red", 13 border: "1px #000 solid", 14 }; 15 var HelloWorld = React.createClass({ 16 render: function () { 17 return <p>Hello, {this.props.name ? this.props.name : "World"}</p>; 18 }, 19 }); 20 var HelloUniverse = React.createClass({ 21 getInitialState: function () { 22 return {name: ''}; 23 }, 24 handleChange: function (event) { 25 this.setState({name: event.target.value}); 26 }, 27 render: function () { 28 return <div> 29 <HelloWorld name={this.state.name}></HelloWorld> 30 <br/> 31 <input type="text" onChange={this.handleChange} /> 32 </div> 33 }, 34 }); 35 React.render(<div style={style}><HelloUniverse></HelloUniverse></div>, document.body); 36 </script> 37 </body> 38 </html>
2.{...props}展开属性
1 <!DOCTYPE html> 2 <html lang="zh-cn"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Hello, World</title> 6 </head> 7 <body> 8 <script src="./react-0.13.2/react-0.13.2/build/react.js"></script> 9 <script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script> 10 <script type="text/jsx"> 11 var style = { 12 color: "red", 13 border: "1px #000 solid", 14 }; 15 var HelloWorld = React.createClass({ 16 render: function () { 17 return <p>Hello, {this.props.name1 + ' ' + this.props.name2}</p>; 18 }, 19 }); 20 var HelloUniverse = React.createClass({ 21 getInitialState: function () { 22 return { 23 name1: 'Tim', 24 name2: 'John', 25 }; 26 }, 27 handleChange: function (event) { 28 this.setState({name: event.target.value}); 29 }, 30 render: function () { 31 return <div> 32 <HelloWorld {...this.state}></HelloWorld> 33 <br/> 34 <input type="text" onChange={this.handleChange} /> 35 </div> 36 }, 37 }); 38 React.render(<div style={style}><HelloUniverse></HelloUniverse></div>, document.body); 39 </script> 40 </body> 41 </html>
3.setProps方法
1 <!DOCTYPE html> 2 <html lang="zh-cn"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Hello, World</title> 6 </head> 7 <body> 8 <script src="./react-0.13.2/react-0.13.2/build/react.js"></script> 9 <script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script> 10 <script type="text/jsx"> 11 var style = { 12 color: "red", 13 border: "1px #000 solid", 14 }; 15 var HelloWorld = React.createClass({ 16 render: function () { 17 return <p>Hello, {this.props.name ? this.props.name : "World"}</p>; 18 }, 19 }); 20 var instance = React.render(<HelloWorld></HelloWorld>, document.body); 21 instance.setProps({name: 'Tim'}); 22 </script> 23 </body> 24 </html>
You can do anything you set your mind to, man!