gpt4 book ai didi

reactjs - 为什么我在构造函数中的绑定(bind)不起作用?

转载 作者:行者123 更新时间:2023-12-05 03:00:22 25 4
gpt4 key购买 nike

在我的 React native 应用程序中,当用户按下一个使用 setState 的按钮 (handleButtonAPressed) 时,我有一个函数,所以我试图用下面的代码在我的构造函数中绑定(bind)它

const handleButtonAPressed = () => {
this.setState({x: this.state.x + 1});
}

export default class SvgExample extends React.Component {

constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
this.handleButtonAPressed = this.handleButtonAPressed.bind(this);
}

render() {
return (
<View>
<RoundButton onPress={handleButtonAPressed} />
</View>
);
}
}

但是,我得到了错误:

'TypeError: undefined is not an object (evaluating '_this2.handleButtonAPressed.bind)

最佳答案

handleButtonAPressed 应该在您的类中,这样您就可以执行 this.handleButtonAPressed.bind(this)。如果你的类中没有 handleButtonAPressedthis.handleButtonAPressed 将是 undefined 并且不可能执行 .bind.

这是你应该做的

export default class SvgExample extends React.Component {

constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
this.handleButtonAPressed = this.handleButtonAPressed.bind(this);
}

handleButtonAPressed() {
this.setState({x: this.state.x + 1});
}

render() {
return (
<View>
<RoundButton onPress={handleButtonAPressed} />
</View>
);
}
}

关于reactjs - 为什么我在构造函数中的绑定(bind)不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56903626/

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