将道具传递给React Router子路由

问题描述 投票:24回答:3

我无法克服反应路由器的问题。 场景是我需要从子状态组件和路由传递子路由一组道具。
我想做的是传递childRouteA它的propsA ,并传递childRouteB它的propsB 。 但是,我能弄清楚如何做到这一点的唯一方法是传递RouteHandler propsApropsB ,这意味着每个子路径都会获得每个子道具而不管它是否相关。 这不是一个阻塞问题,但我可以看到我正在使用两个相同组件的时间,这意味着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()

这实际上就像我期望的那样。 当我链接到/filters/time我得到了Child2组件。 当我去/filters/price我得到了Child1组件。 问题是,这样做这一过程中, Child1Child2都是通过allProps()即使他们只需要价格和时间的道具,分别。 如果这两个组件具有相同的道具名称,这可能会成为一个问题,并且通常不是用不需要的道具来膨胀组件的好方法(因为在我的实际情况中有超过2个子组件)。
总结一下 ,当我进入时间路线( filters/time )时,有没有办法传递RouteHandler timeProps,当我进入价格路线( filters/price )时,只有将RouteHandler传递给RouteHandler并避免将所有道具传递给所有儿童路线?

javascript coffeescript reactjs parent-child react-router
3个回答
29
投票

我遇到了类似的问题,发现你可以访问所设定的道具Route通过this.props.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。 希望这可以帮助!


好的,现在我已经更好地理解了你的问题,这是你可以尝试的。

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

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

路线

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

11
投票

在儿童组件,insted

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

您可以将道具与父项合并

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

0
投票

React.cloneElement可用于呈现子组件,以便传递路径中定义的子路径组件内可用的任何数据。

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

{React.cloneElement(this.props.childRoute, { user: this.props.user })}
© www.soinside.com 2019 - 2024. All rights reserved.