简体   繁体   English

React Native:在静态函数内访问组件状态

[英]React Native : Access Component state inside a static function

I have a component defined like this 我有一个像这样定义的组件

export class A extends Component{
   constructor(props){
     this.state = {
        scene:0
     }
   }
  static changeScene(scene){
     this.setState({scene:scene})
  }
}

I want to call change scene from anywhere using A.changeScene(sceneVal) to change the scene in A. the problem is i can't access this.setState i got this error Unhandled JS Exception: this.setState is not a function. 我想使用A.changeScene(sceneVal)从任何地方调用更改场景来更改A中的场景。问题是我无法访问this.setState我收到此错误Unhandled JS Exception: this.setState is not a function.

I am sure that the A component is already mounted. 我确信A组件已经安装。 I can bypass this error by defining a global variable var self = null; 我可以通过定义一个全局变量var self = null;来绕过这个错误var self = null; and inside the constructor self = this in the constructor but i want a better way to rosolve this problem 并在构造函数self = this中的构造函数,但我想要一个更好的方法来解决这个问题

Reason is, if you use static function then a static method won't be able to access this inside that function. 原因是,如果你使用static function那么static方法将无法在该函数内访问this You should avoid using static function. 你应该避免使用static功能。 Static methods have no access to the values, properties, and methods defined on an instance of the class using this . Static方法必须的值,属性和上所述的实例中定义的方法没有访问class使用this

Check this article: http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx 查看这篇文章: http//odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM