gpt4 book ai didi

javascript - 在 React.js 中使用 handleClick 更改 boolean 值

转载 作者:行者123 更新时间:2023-12-01 02:12:19 36 4
gpt4 key购买 nike

我正在开发一个小组件,它本质上是一个按钮,允许用户单击以查看小型购物车叠加层。

如果“showCart”为 false(也称为未单击按钮),则购物车应该是不可见的。如果单击该按钮,“showCart”应变为 true,从而呈现组件。

我尝试单击该按钮,虽然我确实收到了 console.log 消息“已单击按钮”,但我的购物车叠加层并未出现。谁能给我一些关于为什么这不起作用的见解?

class ViewCart extends React.Component {
constructor(props) {
super(props);
this.state = { showCart: false }
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState ={ showCart: true}
console.log("button clicked")

}
render() {
return (
<div>
<button onClick={this.handleClick}> Show Cart
{this.state.showCart ? <Cart />: null }
</button>

</div>
);
}
}

最佳答案

您没有以正确的方式更改状态,更改状态的代码将如下所示 this.setState({ showCart: true})替换下面代码中的 handleClick 函数。

 handleClick() {
this.setState({ showCart: true})
console.log("button clicked")
}

关于javascript - 在 React.js 中使用 handleClick 更改 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49678310/

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