我正在尝试更新react本机组件中的状态 . 但它的错误,有人可以帮助我 .
我正在使用react-native-cli版本:2.0.1 react-native verions:0.55.4
Here is my code:
import React, { Component } from 'react'
import {
Button,
Text,
View,
} from 'react-native';
export class ToggleButton extends Component {
state = {
isDone: false
};
onAction() {
const value = !this.state.isDone;
this.setState({ isDone: value });
const newValue = this.state.isDone;
console.log(newValue);
}
render() {
return (
<View>
<Button
title="Action"
onPress={this.onAction}
/>
</View>
)
}
}
export default ToggleButton;
3 回答
以下是解决方案
您有三种不同的解决方案 .
在构造函数中绑定您的函数 .
使用实验性公共类字段语法 .
将lambda传递给执行函数 .
问题是您丢失了对
this
的引用,因为该函数未在原始上下文中执行,因此this.setState
不是函数,而是未定义的函数 .在此页面中有所有方法的示例:https://reactjs.org/docs/handling-events.html
更改
至
检查:this