【问题标题】:Resetting state on component in React在 React 中重置组件的状态
【发布时间】:2017-09-19 18:39:57
【问题描述】:

我在 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 函数上显示一个控制台日志,所以我知道它与它如何连接到子组件无关。我是否遗漏了一些关于如何在切换状态值后重置它的内容。感谢您的帮助!

【问题讨论】:

  • 你需要把你的孩子包裹在一个&lt;div&gt;&lt;/div&gt;
  • 您实际上是在调用render 中的函数。当然你的意思是传递函数引用onOpen={this.handleOpen}
  • 对不起,这两个都是错别字。它们已被修复,但问题仍然存在。有什么想法吗?
  • 子组件中如何触发onOpen和onClose

标签: javascript reactjs ecmascript-6 components jsx


【解决方案1】:

你必须这样做!

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')
);

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 2018-10-30
    • 1970-01-01
    • 2019-02-17
    相关资源
    最近更新 更多