[英]How do I stop onClick from rendering when the page renders?
我目前正在将 React 与 Gatsby 和 Material UI 按钮一起使用。 我希望最近按下的按钮具有某个 state。 目前,当我运行我的代码时,我的所有 4 个按钮都被禁用了,因为最近点击的那个被禁用了。 其他帖子说绑定是问题,但我已经在这里做了。 我该怎么做才能使这项工作按预期进行?
这是我在 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
})
}
这是我的按钮渲染的代码:
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>
)
}
我能做些什么??
您将禁用设置为等于 function 但它接受 boolean 值。 这个disable= {() => this.getButtonState(0)}
应该disabled={this.getButtonState(0)}
您无需担心事件处理和绑定 this,因为您无需传递 function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.