React Native:静态函数内部的访问组件状态 [英] React Native : Access Component state inside a static function

查看:34
本文介绍了React Native:静态函数内部的访问组件状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的组件

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})
  }
}

我想使用 A.changeScene(sceneVal)从任何地方调用更改场景更改A中的场景.问题是我无法访问this.setState我收到此错误未处理的JS异常:this.setState不是函数.

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组件已经安装.我可以通过定义一个全局变量 var self = null; 并在构造函数中的构造函数 self = this 中绕过此错误,但是我希望有一种更好的方法来解决此问题

I am sure that the A component is already mounted. I can bypass this error by defining a global variable var self = null; and inside the constructor self = this in the constructor but i want a better way to rosolve this problem

推荐答案

原因是,如果您使用 static函数,则 static 方法将无法访问该函数中的 this .您应该避免使用 static 函数. Static 方法无法使用 this 访问在 class 实例上定义的值,属性和方法.

Reason is, if you use static function then a static method won't be able to access this inside that function. You should avoid using static function. Static methods have no access to the values, properties, and methods defined on an instance of the class using this.

检查本文: http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx

这篇关于React Native:静态函数内部的访问组件状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆