简体   繁体   中英

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

I am currently using React with Gatsby and Material UI Buttons. I want the button that was most recently pressed to have a certain 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. 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:

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. This disable= {() => this.getButtonState(0)} should be 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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