1.一般的数据传输
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script type="text/babel"> class MyComponet extends React.Component{ state={name:"laozhichi",age:18,address:"leizhou"}; render(){ return ( <ul> <li>name is{this.state.name}</li> <li>age is{this.state.age}</li> <li>address is {this.state.address}</li> </ul> ) } } ReactDOM.render(<MyComponet/>,document.getElementById("test")); </script> </body> </html>
2.用props传入数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script type="text/babel"> class MyComponet extends React.Component{ render(){ return ( <ul> <li>name is{this.props.name}</li> <li>age is{this.props.age}</li> <li>address is {this.props.address}</li> </ul> ) } } ReactDOM.render(<MyComponet name="laozhichi" age="19" address="leizhou"/>,document.getElementById("test")); </script> </body> </html>
可以使用console.log(this)查看props参数
3.如果嫌弃老是输入this非常麻烦,可以使用解构的方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script type="text/babel"> class MyComponet extends React.Component{ render(){ const {name,age,address}=this.props; return ( <ul> <li>name is{name}</li> <li>age is{age}</li> <li>address is {address}</li> </ul> ) } } ReactDOM.render(<MyComponet name="lao" age="19" address="leizhou"/>,document.getElementById("test")); </script> </body> </html>