【问题标题】:Change boolean value with handleClick in React.js [duplicate]在 React.js 中使用 handleClick 更改布尔值 [重复]
【发布时间】:2018-09-15 15:03:09
【问题描述】:

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

如果“showCart”为假(也就是未点击按钮),购物车应该是不可见的。如果单击按钮,“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>
        );
  }
}

【问题讨论】:

    标签: javascript reactjs onclick boolean components


    【解决方案1】:

    你没有以正确的方式改变状态,改变状态的代码将是这样的this.setState({ showCart: true}) 从下面的代码中替换handleClick 函数。

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

    【讨论】:

      【解决方案2】:

      您以错误的方式更新您的state :)

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

      【讨论】:

        猜你喜欢
        • 2021-08-03
        • 1970-01-01
        • 2015-01-29
        • 2016-01-30
        • 2014-01-06
        • 2021-12-12
        • 2022-01-15
        • 1970-01-01
        • 2022-01-26
        相关资源
        最近更新 更多