【问题标题】:Access Child state value in Parent component in React在 React 中访问父组件中的子状态值
【发布时间】:2019-08-03 09:12:48
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs components parent-child


    【解决方案1】:

    你可以这样做:

    家长:

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

    【讨论】:

      【解决方案2】:

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

      例如:

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

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

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

      this.props.callback

      【讨论】:

      • 对不起..我不明白你。 &lt;Parent&gt; 是什么,我必须从哪里调用它?
      • 所以,在子组件中,我可以调用this.props.callback。如果我在这个函数中设置状态,那么我可以在App.js 中访问同一个变量吗?如果我错了,你能举个例子吗
      • 您可以将该变量作为参数传递给该回调函数。
      猜你喜欢
      • 2018-07-17
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 2018-09-08
      • 2017-11-12
      • 1970-01-01
      • 2021-09-29
      • 2019-12-07
      相关资源
      最近更新 更多