为什么this.state在原生反应中是未定义的?

我是一个完全新手在反应原生,react.js和JavaScript。 我是Android开发者,所以想给RN一个尝试。

基本上,差别是onPress ;

这个代码在toggle()运行时显示'undefined'

 class LoaderBtn extends Component { constructor(props) { super(props); this.state = { loading: false }; } toggle() { console.log(this.state); // let state = this.state.loading; console.log("Clicked!") // this.setState({ loading: !state }) } render() { return ( <Button style={{ backgroundColor: '#468938' }} onPress={this.toggle}> <Text>{this.props.text}</Text> </Button> ); } } 

但是这个代码工作:

 class LoaderBtn extends Component { constructor(props) { super(props); this.state = { loading: false }; } toggle() { console.log(this.state); // let state = this.state.loading; console.log("Clicked!") // this.setState({ loading: !state }) } render() { return ( <Button style={{ backgroundColor: '#468938' }} onPress={() => {this.toggle()}}> <Text>{this.props.text}</Text> </Button> ); } } 

你能解释一下吗?

在Java / Kotlin中,我们有方法引用,如果签名是相同的,就像onPress = () => {}toggle = () => {}

但在JS中,它不工作:(

在第一个示例toggle()中没有绑定到正确的this

你可以把它绑定在ctor中:

 constructor(props) { super(props); this.toggle = this.toggle.bind(this); ... 

或者使用一个实例函数(在某些情况下确定):

 toggle = () => { ... } 

这种方法需要通过stage-2transform-class-properties构建更改。

具有实例属性函数的警告是有一个每个组件创建的函数。 如果页面上没有很多,这是可以的,但是要记住这一点。

这是基本的JS; 这篇关于React Binding Patterns的文章可能会有帮助。

我认为发生的事情是一个范围问题。 当你使用onPress={this.toggle}这不是你所期待的切换功能。 但是,箭头函数表现出不同的行为,并自动绑定this 。 你也可以使用onPress={this.toggle.bind(this)}

进一步阅读 –

ES6箭头功能

.bind()

这第一个例子中发生的事情就是你已经失去了“这个”的范围。 通常我所做的是在构造函数中定义所有我的函数,如下所示:

 constructor(props) { super(props); this.state = { loading: false }; this.toggle = this.toggle.bind(this); } 

在第二个例子中,你使用的ES6语法将自动绑定这(这就是为什么这个工程)。

然后在你的onPress函数里面,你需要调用你建立的函数。 所以它看起来像这样,

 onPress={this.toggle} 
Interesting Posts