将道具传递给活动的反应路由器处理程序

Passing props to active react router handler

我正在尝试使用 React 实现简单的 CRUD 功能,对不同的路由使用 React 路由器。

我的路线是这样定义的:

<Route path="locations" component={LocationPage}>
  <IndexRoute component={LocationsView}/>
  <Route path="create" component={LocationCreate}/>
  <Route path=":locationSlug">
    <IndexRoute component={LocationsView}/>
    <Route path="edit" component={LocationEdit}/>
  </Route>
</Route>

目前我渲染不同组件的方式在LocationPage中是这样的:

render() {
  return (
    <div>
      <h1>Locations</h1>
      {this.props.children}
    </div>
  );
}

这个问题是我无法将道具传递给每个子组件,即每个子组件都必须获取自己的状态来管理它。但这似乎很荒谬,因为很明显它们是一个逻辑单元,只有 LocationPage 需要知道并保持任何位置的状态。理想情况下,我想将位置作为 props 传递给子组件,但我不明白我怎么能这样做。

我在网上看到过这样的例子:

<RouteHandler {...this.state}/>

这会解决我的问题,但我似乎无法让它工作。我想它早就被贬低了,因为互联网上关于它的很多信息都已经过时了。

我真的不知道如何将道具传递给 this.props.children 而不通过克隆做一些魔术,并以这种方式添加道具,但我想尽可能避免这种情况。

是否有推荐的方法或解决此问题的好方法?任何帮助将不胜感激。

基本概念是遍历 children,克隆它们并插入当前组件的状态和道具。然后函数returnsclonedchildren。见下文:

render: function () {

    return (
        <div>
           <h1>Locations</h1>
           {this._renderedChildren()}
        </div>
    );
  },

  _renderedChildren: function () {
    var renderedChildren = React.Children.map(this.props.children,
      function (child) {
        return React.cloneElement(
        child, Object.assign({}, this.state, this.props)
        );
      }.bind(this)
    );
    return renderedChildren;
  }

Object.assign({}, this.state, this.props) 正在合并 this.state 和 this.props。 React.cloneElement(child, props) 使用指定的道具制作一个新的反应元素。

我最终只是实现了自己的 RouteHandler。实施:

export default (props) => {
  // prevent childception
  let propsToPass = {};
  Object.keys(props).forEach(key =>
    (key.localeCompare('children') !== 0) && (propsToPass[key] = props[key])
  );
  return <div>
    {props.children && React.cloneElement(props.children, { ...propsToPass })}
  </div>
}

以及用法:

render() {
  return (
    <div>
      <h1>Locations</h1>
      <RouteHandler
        locations={this.props.locations}
        selectedLocation={this.props.selectedLocation}>
        {this.props.children}
      </RouteHandler>
    </div>
  );
}

这实现了我想要的功能,而没有在代码中引入太多样板。希望这可以帮助某人,如果有人遇到这个问题。

我最终并没有真​​正使用它,因为最终,这个组件变得太大了,并且对我的喜好承担了太多的责任,所以我最终最终将处理逻辑移到了子组件中,这似乎两害相权取其轻。