1
我在React JS中有一個簡單的問題。我有兩個不同的點擊事件,它們切換組件的狀態。第一個完美的工作,但我不能得到第二個事件重置組件回到其原始狀態。這是我的問題的簡化版本,所以只知道我不能將點擊功能移動到Child組件中。在React中重置組件的狀態
class Parent extends Component{
constructor(){
this.state = {
open: false
}
this.handleOpen = this.handleOpen.bind(this)
this.handleClose = this.handleClose.bind(this)
}
handleOpen(){
this.setState({open: true})
}
handleClose(){
this.setState({open: false})
}
render(){
return(
<div>
<Child onOpen={this.handleOpen} onClose={this.handleClose} />
<Child onOpen={this.handleOpen} onClose={this.handleClose} />
<Child onOpen={this.handleOpen} onClose={this.handleClose} />
<Child onOpen={this.handleOpen} onClose={this.handleClose} />
</div>
)
}
}
就像我說的,handleOpen
功能切換狀態,但handleClose
不切換回來。我可以獲得一個控制檯日誌以顯示handleClose
函數,所以我知道它不必關心它是如何連接到子組件的。我錯過了關於如何在已經切換之後重置狀態值的情況。感謝您的幫助!
你需要用你的孩子在一個''
–你實際上調用'render'的功能。當然你的意思是傳遞函數參考'onOpen = {this.handleOpen}'< - 沒有圓括號 – azium
對不起,這些都是錯別字。它們已被修復,但問題仍然存在。有任何想法嗎? –