1,https://juejin.cn/post/7001645745594400776
- 类式组件中的构造器完全可以省略
- 若写了构造器,super必须调用
- 需要在构造器中通过this.props访问,那么props必须传值给super
<script type="text/babel"> class Demo extends React.Component { constructor(props) { super(props) this.state = {isHot: true} // 解决方法:给实例自身追加一个同名的getIsHot方法,这个方法是根据原型上的getIsHot用bind生成的,它的this指向没问题 // 注意:类中的方法是绑在原型对象上的,没有绑在实例上,如下可以给实例绑定同名方法 this.getIsHot = this.getIsHot.bind(this) } render() { console.log(this) const {isHot} = this.state // 问题:为什么this是undefined // 此时的getisHot函数是作为点击事件的回掉函数,根本就不是通过Weather的实例对象调用的 // 而且类中的方法自动开启严格模式,所以this是undefined return <h1 onClick={this.getIsHot}>今天天气很{isHot ? '炎热': '凉爽'}</h1> } getIsHot(){ // state不能直接修改,要用setStatae去修改 如下 // this.state.isHot = ! this.state.isHot const isHot = this.state.isHot this.setState({isHot: !isHot}) } } ReactDOM.render(<Demo/>, document.getElementById('test')) </script>
浙公网安备 33010602011771号