1.getInitialState:设置初始State,返回Object
2.this.setState():改变State
3.都在creatClass内创建类
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"> <script src="lib/react.js"></script> <script src="lib/react-dom.js"></script> <script src="lib/browser.min.js"></script> <title></title> </head> <body> <div id="example"></div> </body> <script type="text/babel"> var LikeButton = React.createClass({ getInitialState: function() { return {liked: false}; }, handleClick: function(event) { this.setState({liked: !this.state.liked}); }, render: function() { var text = this.state.liked ? ‘喜欢‘ : ‘不喜欢‘; return ( <p onClick={this.handleClick}> 你<b>{text}</b>我。点我切换状态。 </p> ); } }); ReactDOM.render( <LikeButton />, document.getElementById(‘example‘) ); </script> </html>
时间: 2024-11-03 05:37:57