简体   繁体   English

如何在页面呈现时停止 onClick 呈现?

[英]How do I stop onClick from rendering when the page renders?

I am currently using React with Gatsby and Material UI Buttons.我目前正在将 React 与 Gatsby 和 Material UI 按钮一起使用。 I want the button that was most recently pressed to have a certain state.我希望最近按下的按钮具有某个 state。 Currently, When I run my code, all 4 of my buttons are getting disabled because the one that was most recently clicked gets disabled.目前,当我运行我的代码时,我的所有 4 个按钮都被禁用了,因为最近点击的那个被禁用了。 Other posts have said that binding was the problem, but I am already doing it here.其他帖子说绑定是问题,但我已经在这里做了。 What can I do to make this work as expected?我该怎么做才能使这项工作按预期进行?

This is the code for the function that I wrote in the class:这是我在 class 中编写的 function 的代码:

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
        })
    }

This is the code for my button render:这是我的按钮渲染的代码:

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>
   )
 }

What can I do??我能做些什么??

You are setting disable equal to a function but it accepts a boolean value.您将禁用设置为等于 function 但它接受 boolean 值。 This disable= {() => this.getButtonState(0)} should be disabled={this.getButtonState(0)}这个disable= {() => this.getButtonState(0)}应该disabled={this.getButtonState(0)}

You don't need to worry about event handling and binding this, because you don't need to pass a function您无需担心事件处理和绑定 this,因为您无需传递 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM