【发布时间】:2017-10-09 03:34:30
【问题描述】:
我想在我的父组件 in this example 中使用我的子组件的状态。我想要做的是:
<Application onChange={(myVar)=>{console.log(myVar)}}/>
【问题讨论】:
标签: javascript reactjs react-jsx
我想在我的父组件 in this example 中使用我的子组件的状态。我想要做的是:
<Application onChange={(myVar)=>{console.log(myVar)}}/>
【问题讨论】:
标签: javascript reactjs react-jsx
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
【讨论】: