前一段帮人解决一个bug,用了static,出现了this is undefined的错误,所以特地纠结了一下static的具体用法
the methods do not have access to the props or state of your components.
React默认不能通过static修改state。
一. 区分类和实例
static方法属于类,而setState是对象的方法,所以在static function内使用this会报错。static创建了一个属于类的方法或者属性,而不属于任何实例。
组件是类的一个实例,component的props和state都属于实例。
static function stateTest (){
this.setState({ //报错
})
}
setState作为对象的方法,在类方法中调用对象方法,因为无法确定类中有多少个对象,所以会找不到this
二. 组件中调用静态方法
class stateComponent extends React.Component {
static function stateTest (){
}
....
// 调用
stateComponent.stateTest()
}