简体   繁体   English

在React中重置组件的状态

[英]Resetting state on component in React

I have a simple problem in React JS. 我在React JS中有一个简单的问题。 I have two different click events, which switch the state of the component. 我有两个不同的点击事件,它们切换组件的状态。 The first one works perfectly, however I cannot get the second event to reset the component back to its original state. 第一个工作完美,但我不能得到第二个事件将组件重置回其原始状态。 This is a stripped down version of my problem, so just know that I cannot move the click functions into the Child component. 这是我的问题的精简版,所以只知道我无法将点击功能移动到子组件中。

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>
    )
  }
}

Like I said, the handleOpen function switches the state, but the handleClose does not switch it back. 就像我说的那样, handleOpen函数会切换状态,但handleClose不会将其切换回来。 I can get a console log to show on the handleClose function, so I know that it does not have to do with how it is being hooked up to the Child Component. 我可以在handleClose函数上显示一个控制台日志,所以我知道它与如何连接到Child Component没有关系。 Am I missing something about how to reset a state value after it has already been switched. 我错过了关于如何在状态值切换后重置状态值的内容。 Thank you for your help! 谢谢您的帮助!

Here is How you have to do it! 这是你必须要做的!

 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