简体   繁体   English

在React的父组件中访问子状态值

[英]Access Child state value in Parent component in React

I have (eg) two components in React. 我在React中有两个组件。 First one App.js is a parent component. 第一个App.js是父组件。 It pass some values to the child component Child.js . 它将一些值传递给子组件Child.js In child.js, it receives the values via props and update some state variables using axios call results. child.js,它通过接收值props和更新一些state使用变量axios通话效果。 this works fine. 这很好。

Now I need to get that updates result value in App.js . 现在,我需要在App.js获取更新结果值。 how to get that value in App.js ? 如何在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 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. 其中this.callbackfn将是您父组件中的一个函数。

From child component you can call it as 在子组件中,您可以将其称为

this.props.callback 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)
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM