【问题标题】:ReactJs get the state of child componentReactJs 获取子组件的状态
【发布时间】:2017-10-09 03:34:30
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs react-jsx


    【解决方案1】:

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

    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);
      }
    
      //.....
    
    }
    

    更新的 Codepen:https://codepen.io/anon/pen/gWvKxa

    【讨论】:

      猜你喜欢
      • 2018-10-05
      • 2020-06-06
      • 2019-11-27
      • 2017-11-05
      • 1970-01-01
      • 2018-09-29
      • 2020-09-17
      • 2021-06-08
      • 2015-04-15
      相关资源
      最近更新 更多