在真实的类组件中,不会出现构造器,想把自定义的属性添加到实例对象上,在类中直接赋值即可,但切记:只有固定的值才可能这样写,如果赋的是一个变量,还是要写构造器
class Weather extends React.Component {
// constructor(props) {
// super(props)
// this.state = { isHot: false, wind: '风' }
// this.newWeather = this.changeWeather.bind(this)
// }
state = { isHot: false, wind: '风' } // 往weather的实例对象的state上添加属性
}
在真实的类组件中,也无需大量的操作自定义方法的this指向,显得代码很冗余,自定义方法——用赋值语句的形式+箭头函数
class Weather extends React.Component {
/*
箭头函数没有自己的this,他找其外层函数的this去作为自己的this
*/
// 原本自定义的changeWeather方法是挂载在weather的原型对象上,但是这样用箭头函数赋值写后,changeWeather方法就挂在在weather的实例对象身上
changeWeather = () => {
const isHot = this.state.isHot
this.setState({ isHot: !isHot })
console.log(this) // weather的实例对象
}
}