将 props 传递给 React Router children 路由

Passing props to React Router children routes

我在克服 React 路由器的问题时遇到了问题。场景是我需要通过 children 路由一组来自状态 parent 组件和路由的道具。
我想做的是将 childRouteA 传递给 propsA,并将 childRouteB 传递给 propsB。但是,我能弄清楚如何做到这一点的唯一方法是同时传递 RouteHandler propsApropsB,这意味着每个 child 路由都会得到每个 child 道具不管它是否相关。目前这不是一个阻塞问题,但我可以看到有一段时间我会使用同一组件的两个,这意味着 propA 上的键将被 propB 上的键覆盖。

# routes
routes = (
  <Route name='filter' handler={ Parent } >
    <Route name='price' handler={ Child1 } />
    <Route name='time' handler={ Child2 } />
  </Route>
)

# Parent component
render: ->
  <div>
    <RouteHandler {...@allProps()} />
  </div>

timeProps: ->
  foo: 'bar'

priceProps: ->
  baz: 'qux'

# assign = require 'object-assign'
allProps: ->
  assign {}, timeProps(), priceProps()

这实际上按照我期望的方式工作。当我 link 到 /filters/time 时,我得到 Child2 组件呈现。当我转到 /filters/price 时,我得到了呈现的 Child1 组件。问题是,通过执行此过程,Child1Child2 都通过了 allProps(),即使它们分别只需要价格和时间道具。如果这两个组件具有相同的 prop 名称,这可能会成为一个问题,并且通常不是用不需要的 props 膨胀组件的好习惯(因为在我的实际情况下有超过 2 children)。
所以总而言之,有没有办法在我去时间路线(filters/time)时传递RouteHandler timeProps并且只将priceProps传递给RouteHandler 当我去价格路线 (filters/price) 并避免将所有道具传递给所有 children 路线时?

我 运行 遇到了类似的问题,发现您可以在路由组件中通过 this.props.route 访问 Route 上设置的道具。知道这一点后,我这样组织了我的组件:

index.js

React.render((
  <Router history={new HashHistory()}>
    <Route component={App}>
        <Route
          path="/hello"
          name="hello"
          component={views.HelloView}
          fruits={['orange', 'banana', 'grape']}
        />
    </Route>
  </Router>
), document.getElementById('app'));

App.js

class App extends React.Component {
  constructor(props) {
    super(props);
  }

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

HelloView.js

class HelloView extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <div>
      <ul>
        {this.props.route.fruits.map(fruit => 
          <li key={fruit}>{fruit}</li>
        )}
      </ul>
    </div>;
  }
}

这是使用 react-router v1.0-beta3。希望这对您有所帮助!


好的,现在我对你的问题有了更好的了解,你可以尝试以下方法。

由于您的子 props 来自单个父组件,因此您的父组件(而不是 react-router)应该管理渲染哪个子组件,以便您可以控制传递哪些 props。

您可以尝试更改路由以使用参数,然后在父组件中检查该参数以呈现适当的子组件。

路线

<Route name="filter" path="filter/:name" handler={Parent} />

父组件

render: function () {
  if (this.props.params.name === 'price') {
    return <Child1 {...this.getPriceProps()} />
  } else if (this.props.params.name === 'time') {
    return <Child2 {...this.getTimeProps()} />
  } else {
    // something else
  }
}

在子组件中,而不是

return <div>{this.props.children}</div>

您可以将道具与父道具合并

var childrenWithProps = React.cloneElement(this.props.children, this.props);
return <div>{childrenWithProps}</div>

React.cloneElement 可用于呈现子组件,从而传递在路由中定义的子路由组件内可用的任何数据。

例如,这里我将 user 的值传递给 react childRoute 组件。

{React.cloneElement(this.props.childRoute, { user: this.props.user })}