[英]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.