gpt4 book ai didi

javascript - 为什么 this.state 在 React Native 中未定义?

转载 作者:行者123 更新时间:2023-12-03 13:07:15 25 4
gpt4 key购买 nike

我是 React Native、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() 未绑定(bind)到正确的 this

您可以在构造函数中绑定(bind)它:

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

或者使用实例函数(在某些情况下可以):

toggle = () => {
...
}

此方法需要通过 stage-2transform-class-properties 进行构建更改。

实例属性函数需要注意的是,每个组件都会创建一个函数。如果页面上的内容不多,这也没关系,但请记住这一点。一些模拟库也不能很好地处理箭头函数(即箭头函数不在原型(prototype)上,而是在实例上)。

这是基本的JS; this article regarding React Binding Patterns可能有帮助。

关于javascript - 为什么 this.state 在 React Native 中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43074758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com