将道具传递给React Router子路径

时间:2015-08-06 18:06:45

标签: javascript coffeescript reactjs parent-child react-router

我无法克服反应路由器的问题。场景是我需要从子状态组件和路由传递子路由一组道具 我想要做的是通过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个孩子)。
总结如何,当我转到时间路线(RouteHandler)时,有没有办法传递filters/time timeProps,只有当我发送时才将priceProps传递给RouteHandler转到价格路线(filters/price)并避免将所有道具传递给所有儿童路线?

3 个答案:

答案 0 :(得分:28)

我遇到了类似的问题,发现您可以访问路径组件中Routethis.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
  }
}

答案 1 :(得分:11)

在儿童组件中,

的内容
return <div>{this.props.children}</div>

您可以将道具与父

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

答案 2 :(得分:0)

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

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

{React.cloneElement(this.props.childRoute, { user: this.props.user })}
相关问题