Phi*_*arg 24 javascript parent-child coffeescript reactjs react-router
我无法克服反应路由器的问题.场景是我需要从子状态组件和路由传递子路由一组道具.
我想做的是通过childRouteA
它propsA
,并通过childRouteB
它propsB
.然而,我能弄清楚如何做到这一点的唯一方法是传递RouteHandler
两者propsA
,propsB
这意味着每条儿童路线都会获得每个儿童道具,无论其是否相关.这不是一个阻塞问题,但我可以看到我正在使用两个相同组件的时间,这意味着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()
Run Code Online (Sandbox Code Playgroud)
这实际上就像我期望的那样.当我链接到/filters/time
我得到Child2
渲染的组件.当我去/filters/price
我得到Child1
组件渲染.问题是,做这个过程,Child1
并且Child2
都通过了allProps()
,即使他们只需要价格和时间的道具,分别.如果这两个组件具有相同的道具名称,这可能会成为一个问题,并且通常不是用不需要的道具来膨胀组件的好方法(因为在我的实际情况中有超过2个子组件).
所以总结一下,RouteHandler
当我去时间路线(filters/time
)时,有没有办法传递timeProps ,只有RouteHandler
当我去价格路线(filters/price
)并且避免将所有道具传递给所有子路线时才传递priceProps ?
Jim*_*itt 29
我遇到了类似的问题,发现你可以访问所设定的道具Route
,通过this.props.route
在路线的组成部分.知道了这一点,我组织了这样的组件:
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'));
Run Code Online (Sandbox Code Playgroud)
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div>{this.props.children}</div>;
}
}
Run Code Online (Sandbox Code Playgroud)
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>;
}
}
Run Code Online (Sandbox Code Playgroud)
这是使用react-router v1.0-beta3.希望这可以帮助!
好的,现在我已经更好地理解了你的问题,这是你可以尝试的.
由于您的子道具来自单个父级,因此您的父组件(而不是react-router)应该是管理哪个子项被渲染的组件,以便您可以控制传递哪些道具.
您可以尝试更改路由以使用参数,然后检查父组件中的该参数以呈现相应的子组件.
<Route name="filter" path="filter/:name" handler={Parent} />
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*arc 11
在儿童组件,insted
return <div>{this.props.children}</div>
Run Code Online (Sandbox Code Playgroud)
您可以将道具与父项合并
var childrenWithProps = React.cloneElement(this.props.children, this.props);
return <div>{childrenWithProps}</div>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24458 次 |
最近记录: |