-1
我想在我的父组件in this example中使用我的子组件的状态。正是我想要能够做的是这样的:ReactJs获取子组件的状态
<Application onChange={(myVar)=>{console.log(myVar)}}/>
我想在我的父组件in this example中使用我的子组件的状态。正是我想要能够做的是这样的:ReactJs获取子组件的状态
<Application onChange={(myVar)=>{console.log(myVar)}}/>
你onChange
只是其中传递到您的应用程序组件正常的道具。所以如果它是一个函数,你可以随时调用它。在这种情况下,更新应用程序的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);
}
//.....
}
更新Codepen:https://codepen.io/anon/pen/gWvKxa