我想在我的父组件in this example中使用我的子组件的状态。我真正希望能够做到的是:
<Application onChange={(myVar)=>{console.log(myVar)}}/>
答案 0 :(得分:1)
你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