[英]Access Child state value in Parent component in React
我在React中有两个组件。 第一个App.js
是父组件。 它将一些值传递给子组件Child.js
。 在child.js,
它通过接收值props
和更新一些state
使用变量axios
通话效果。 这很好。
现在,我需要在App.js
获取更新结果值。 如何在App.js
获得该值?
App.js
this.state ({ ...
examResult: null // need to update this with the child component result.
})
<ChildComponent
Id={this.state.StudentId}
Name={this.state.StudentName}
/>
Child.js
state {
examResult: null
}
...
componentDidMount()
{
const {Id, Name} = this.props;
axios.get( .... //To get the Result
this.setState(
{ examResult: examResult} //Update the result to state variable. It wors fine. I need to pass this value to App.js
)
}
您可以传递其他功能作为道具。 从子组件中,您可以调用该函数并在父组件中传递所需的任何参数。
例如:
<ChildComponent
Id={this.state.StudentId}
callback={this.callbackfn}
Name={this.state.StudentName} />
其中this.callbackfn将是您父组件中的一个函数。
在子组件中,您可以将其称为
this.props.callback
您可以这样做:
上级:
updateResults(results) {
this.setState({examResult:results});
}
render() {
return (<ChildComponent
Id={this.state.StudentId}
Name={this.state.StudentName}
updateResults={this.updateResults.bind(this)}
/>)
}
儿童:
componentDidMount()
{
const {Id, Name, updateResults} = this.props;
axios.get( ....).then(results => //To get the Result
updateResults(results.data)
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.