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

Access Child state value in Parent component in React

我有(例如)React 中的两个组件。第一个 App.js 是父组件。它将一些值传递给子组件 Child.js。在 child.js, 中,它通过 props 接收值并使用 axios 调用结果更新一些 state 变量。这很好用。

现在我需要在 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
    )
}

您可以将另一个函数作为 props 传递。从子组件中,您可以调用该函数并在父组件中传递您需要的任何参数。

例如:

<ChildComponent 
    Id={this.state.StudentId} 
    callback={this.callbackfn}
    Name={this.state.StudentName} />

其中 this.callbackfn 将是您父组件中的一个函数。

在子组件中,您可以将其称为

this.props.callback

你可以这样做:

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)
    )
}