I have (eg) two components in React. First one App.js
is a parent component. It pass some values to the child component Child.js
. In child.js,
it receives the values via props
and update some state
variables using axios
call results. this works fine.
Now I need to get that updates result value in App.js
. how to get that value in 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
)
}
You can pass another function as props. And from child component you can call that function and pass whatever parameters you need in your parent component.
Ex:
<ChildComponent
Id={this.state.StudentId}
callback={this.callbackfn}
Name={this.state.StudentName} />
Where this.callbackfn will be a function in your parent component.
From child component you can call it as
this.props.callback
You can do it like this:
Parent:
updateResults(results) {
this.setState({examResult:results});
}
render() {
return (<ChildComponent
Id={this.state.StudentId}
Name={this.state.StudentName}
updateResults={this.updateResults.bind(this)}
/>)
}
Child:
componentDidMount()
{
const {Id, Name, updateResults} = this.props;
axios.get( ....).then(results => //To get the Result
updateResults(results.data)
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.