javascript - react native : Access Component state inside a static function

标签 javascript reactjs react-native ecmascript-6

我有一个这样定义的组件

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/

相关文章:

javascript - Angularjs:捕获浏览器中的刷新事件

javascript - farbtastic 插件回调函数

javascript - 带有 XmlHttpRequest 的 DataURI

Reactjs,this.context 已弃用

reactjs - 如何使用 React Context API?

android - Youtube iframe 视频在 react-native webview 中不起作用

javascript - 平滑 'turning'脚本

reactjs - 在 Material UI 的 <ExpansionPanelDetails> 中保留新行

react-native - Appcelerator Titanium 和 React Native 的主要区别

android - React Native 中适用于 ios 和 Android 的自定义字体