ReactJs 获取子组件的状态

ReactJs get the state of child component

我想在我的父组件中使用我的子组件的状态 in this example。我真正想要做的是:

<Application onChange={(myVar)=>{console.log(myVar)}}/>

onChange 只是您传递到应用程序组件中的一个普通道具。因此,如果它是一个函数,您可以随时调用它。在这种情况下,在 Application 的 state 更新时调用它更有意义。您可以使用 setState 函数的第二个参数,这是一个可选的回调函数。但是只要确保你 onChange prop 被定义并且它是一个函数,然后你用你想要传递的任何参数调用它。

class Application extends React.Component {
  constructor(props){
    super(props);
    this.state = {myVar:0};
    setInterval(()=>{
      this.setState( { myVar:this.state.myVar + 1 }, () => {
        if(this.props.onChange && typeof this.props.onChange === "function")
          this.props.onChange(this.state.myVar)
      } ); 
      }, 3000);
  }

  //.....

}

更新的代码笔:https://codepen.io/anon/pen/gWvKxa