首页 > 解决方案 > 如何在页面呈现时停止 onClick 呈现?

问题描述

我目前正在将 React 与 Gatsby 和 Material UI 按钮一起使用。我希望最近按下的按钮具有某种状态。目前,当我运行我的代码时,我的所有 4 个按钮都被禁用了,因为最近点击的那个被禁用了。其他帖子说绑定是问题,但我已经在这里做了。我该怎么做才能使这项工作按预期进行?

这是我在课堂上编写的函数的代码:

constructor() {
      super()
      this.state = {
          pressed: [true, false, false, false],
          current: 0
      }
    }


getButtonState = location => {
    return this.state.pressed[location]
}

changeButtonState(location){
        const newState = this.state.pressed.slice() //copy the array
        newState[location] = true //execute the manipulations
        newState[this.state.current] = false
        this.setState({
            pressed: newState,
            current: location
        })
    }

这是我的按钮渲染的代码:

render() {
   return(
     <div>
       <Button variant="outlined" color="primary" disabled={ () => this.getButtonState(0) } 
        onClick={() => {this.changeButtonState(0)}} style={{ borderRadius: 25, margin: 4 }}>All</Button>
       <Button variant="outlined" color="primary" disabled={ () => this.getButtonState(1) } 
         onClick={() => {this.changeButtonState(1)}} style={{ borderRadius: 25, margin: 4 }}>Mechanical</Button>
       <Button variant="outlined" color="primary" disabled={ () => this.getButtonState(2)} 
         onClick={() => {this.changeButtonState(2)}} style={{ borderRadius: 25, margin: 4  }}>Software</Button>
       <Button variant="outlined" color="primary" disabled={ () => this.getButtonState(3)} 
         onClick={() => {this.changeButtonState(3)}} style={{ borderRadius: 25, margin: 4  }}>Design</Button>
     </div>
   )
 }

我能做些什么??

标签: javascriptreactjsmaterial-uigatsby

解决方案


您将禁用设置为等于一个函数,但它接受一个布尔值。这disable= {() => this.getButtonState(0)}应该是disabled={this.getButtonState(0)}

您无需担心事件处理和绑定 this,因为您不需要传递函数


推荐阅读