gpt4 book ai didi

javascript - 计数器应用程序无法在 React 上运行

转载 作者:行者123 更新时间:2023-11-28 17:28:15 24 4
gpt4 key购买 nike

我创建了 2 个按钮,并希望它们通过单击每个按钮来增加其值。下面的代码不起作用。请帮忙 !所有这些代码我都在带有 buttons 类的 html 标记中呈现。

class Buttons extends React.Component {
state = { score_1: 0, score_2: 0 };

updateScore_1() {
this.setState((prevState) => {
score_1: prevState.score_1 += 1
});
}
updateScore_2() {
this.setState((prevState) => {
score_2: prevState.score_2 += 1
});
}
render() {
return (
<div>
<button onClick={this.updateScore_1.bind(this)}>{this.state.score_1}</button>
<br />
<button onClick={this.updateScore_2.bind(this)}>{this.state.score_2}</button>
</div>
)
}
}
ReactDOM.render(
<Buttons />,
document.querySelector('.buttons')
);

最佳答案

您错过了 this.setState 中的关键字 return。只需在 this.setState 中添加 return 即可:

updateScore_2() {
this.setState((prevState) => {
return { score_2: prevState.score_2 + 1 }
});
}

关于javascript - 计数器应用程序无法在 React 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51056569/

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