浅谈React之状态(State)(2)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #myDiv{ width:200px; height:400px; background:red; color:yellow; border:1px solid green; } </style> <script src="https://zhangpeiyue.com/wp-content/uploads/2018/08/react.development.js"></script> <script src="https://zhangpeiyue.com/wp-content/uploads/2018/08/react-dom.development.js"></script> <script src="https://zhangpeiyue.com/wp-content/uploads/2018/08/babel.min_.js"></script> </head> <body> <div></div> </body> <script type="text/babel"> class MyComponent extends React.Component{ constructor(props){ super(props); // 为当前状态添加isShow属性 this.state={ // 值为true显示,false为隐藏。默认值为true。 isShow:true } } changeState(){ //此处不能直接修改isShow的值。而是需要借助setState方法! this.setState({ //取反操作 isShow:!this.state.isShow }); } render(){ //返回组件的初始内容 return <div> {/*在ES6的class中React是不会自动绑定this的,所以需要自己绑定*/} <input type="button" value="显示与隐藏" onClick={this.changeState.bind(this)} /> <div style={{display:this.state.isShow?'block':'none'}}> 我在这里呀! </div> </div> } } ReactDOM.render( <MyComponent/>, document.querySelector("#wrap") ) </script> </html>

由上面的示例可以发现,当你改变isShow的状态时,div也会发生相对应的变化!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/2c414a073e66779b02ad35027ea5e52a.html