[英]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.