我有一个这样定义的组件
export class A extends Component{
constructor(props){
this.state = {
scene:0
}
}
static changeScene(scene){
this.setState({scene:scene})
}
}
我想使用 A.changeScene(sceneVal)
从任何地方调用更改场景
更改 A 中的场景。问题是我无法访问 this.setState 我收到此错误 Unhandled JS Exception: this.setState is not a function.
我确定 A 组件已经安装。我可以通过在构造函数中定义一个全局变量 var self = null;
并在构造函数内部 self = this
来绕过这个错误,但我想要一个更好的方法来解决这个问题
最佳答案
原因是,如果您使用static function
,则static
方法将无法访问该函数内的this
。您应该避免使用 static
函数。 静态
方法无法访问使用this
在类
的实例上定义的值、属性和方法。
查看这篇文章:http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx
关于javascript - react native : Access Component state inside a static function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42373580/