这更多是关于响应而不是特定问题的体系结构问题,但是,使用布局组件和几个基于URL呈现的子组件来管理状态/道具的最佳实践是什么?
可以说我有类似以下代码的内容:一个配置文件页面(主布局视图),带有用于配置文件子部分(设置,首选项,帐户详细信息等)的导航链接,以及一个主面板,其中显示了每个子部分。
所以目前我会 遇到 这样的事情:我的路由器 route.js
<Router history={browserHistory}> <Route path='/profile' component={Profile} > <IndexRoute component={Summary} /> <Route path='/profile/settings' component={Settings} /> <Route path='/profile/account' component={Account} /> <Route path='/profile/preferences' component={Preferences} /> </Route> </Router>
以及我的个人资料布局组件 profile.js* 的精简版 *
class Profile extends React.Component { constructor(props) { super(props) } render(){ let pathName = this.props.location.pathname; return( <div className='container profile-page'> <div className='side-nav'> <ul> <li><Link to='/profile'>Summary</Link></li> <li><Link to='/profile/settings'>Settings</Link></li> <li><Link to='/profile/account'>My Account</Link></li> <li><Link to='/profile/preferences'>Preferences</Link></li> </ul> </div> <div className='main-content'> {this.props.children} </div> </div> ) } } export default Profile;
所以这种作品。子组件将根据url呈现。但是那我该如何管理状态和道具呢?以我对React和Flux的理解,我希望Profile组件能够管理状态并监听商店中的更改,并将这些更改传播到其子级。这样对吗?
我的问题是,似乎没有一种直观的方式将道具传递给由this.props.children渲染的组件,这使我感到我当前的体系结构和/或对通量的理解不正确。
一点指导将不胜感激。
我觉得你在做什么很好。您走在正确的道路上。
React为您提供了多种API,它们将完全照顾您不确定如何实现的(way to pass props to components rendered by this.props.children)
way to pass props to components rendered by this.props.children
首先,您需要看一看cloneElement
基本上它将使用一个React元素,将其克隆,然后返回另一个props,您可以根据需要完全更改,更改或替换这些props。
此外,将其与Children Utilities结合使用-遍历提供给顶层组件的子代,并分别对每个元素进行必要的更改。
提议的示例用法可能很简单
<div className='main-content'> {React.children.map(this.props.children, (child, index) => { //Get props of child const childProps = child.props; //do whatever else you need, create some new props, change existing ones //store them in variables return React.cloneElement(child, { ...childProps, //these are the old props if you don't want them changed ...someNewProps, someOldPropOverwritten, //overwrite some old the old props }); )} </div>
使用这些工具可以在任何地方创建真正通用且可重用的组件。从更常用工具Children是map,forEach和toArray。每个都有自己的目标。
Children
map
forEach
toArray
希望这可以帮助。