【问题标题】:How can I set the state of my parent component from the child component when using react-router?使用 react-router 时如何从子组件设置父组件的状态?
【发布时间】:2018-01-02 02:59:49
【问题描述】:

我正在开发一个 React 项目,其中将提示用户一系列问题,这些问题的答案将组合为要保存的对象。

父组件包含多个子组件。

例如——

<Route path="Parent" component={Parent}>
    <Route path="Child1" component={Child1} />
    <Route path="Child2" component={Child2} />
    <Route path="Child3" component={Child3} />
    <IndexRoute component={Child1} />
</Route>

父级将具有空值的初始状态 前任。 (this.state={value1:"", value2:""})

在使用 {this.props.children} 时,如何将数据从子级传递给父级(以及从父级传递给子级的道具)?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    不要使用component 属性来渲染您的子路由,而是使用render 属性。这使您可以让函数返回要呈现的组件,而不是简单地接受类本身。它看起来像这样:

    <Route path="Parent" component={Parent}>
        <Route path="Child1" render={() => {<Child1 someProp={foo} />}} />
        <Route path="Child2" render={() => {<Child2 someProp={bar} />}} />
        <Route path="Child3" render={() => {<Child3 someProp={baz} />}} />
        <IndexRoute component={Child1} />
    </Route>
    

    为什么要这样做呢?好吧,正如您所看到的,现在您可以将道具传递给渲染的孩子(在本例中,someProp)。现在你可以将道具传递给孩子,这对use callbacks to modify parent state from the children.来说是微不足道的

    More info on the render prop here.

    【讨论】:

    • 太棒了。请同时考虑完全不要使用state,并将实现移至StateManager,例如Redux
    • 对于 react router v4,这是一个首选的方式,只要确保使用渲染而不是组件,以避免额外的安装和重新渲染。
    【解决方案2】:

    为了让父级从其子级获取数据,您需要将回调函数作为属性传递给该子级。

    callbackFunction(data) {
        // do something
    }
    
    <ChildComponent parentCallback={this.callbackFunction} />
    

    然后你可以使用子组件内部的 prop 将数据发送回它的父组件,然后它会使用回调函数对它做一些事情。

    const x = ["a", "b", "c", "d"];
    this.props.parentCallback(x);
    

    查看以下文章了解更多详情:https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17

    另一种选择是使用像 Redux 这样的状态容器。在这种情况下,您的子组件会将值分派给一个状态,并且该状态正在由其父级监听,当状态更改时将重新渲染。这是更复杂场景的解决方案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 2021-03-14
      • 2020-10-06
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      相关资源
      最近更新 更多