簡體   English   中英

在React中重置組件的狀態

[英]Resetting state on component in React

我在React JS中有一個簡單的問題。 我有兩個不同的點擊事件,它們切換組件的狀態。 第一個工作完美,但我不能得到第二個事件將組件重置回其原始狀態。 這是我的問題的精簡版,所以只知道我無法將點擊功能移動到子組件中。

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函數上顯示一個控制台日志,所以我知道它與如何連接到Child Component沒有關系。 我錯過了關於如何在狀態值切換后重置狀態值的內容。 謝謝您的幫助!

這是你必須要做的!

 class Child extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { console.log(this.props.isOpen); if (this.props.isOpen) { this.props.onClose(); } else { this.props.onOpen(); } } render() { return <button onClick={this.handleClick}>Click ME</button>; } } class Parent extends React.Component{ constructor(props){ super(props); 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> <p>{this.state.open.toString()}</p> <Child onOpen={this.handleOpen} onClose={this.handleClose} isOpen={this.state.open} /> <Child onOpen={this.handleOpen} onClose={this.handleClose} isOpen={this.state.open} /> <Child onOpen={this.handleOpen} onClose={this.handleClose} isOpen={this.state.open} /> <Child onOpen={this.handleOpen} onClose={this.handleClose} isOpen={this.state.open} /> </div> ) } } ReactDOM.render( <Parent/>, document.getElementById('container') ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM