jmk*_*oll 5 javascript flux reactjs
这是一个关于反应而不是特定问题的架构问题,但是什么被认为是使用布局组件管理状态/道具的最佳实践,以及基于URL呈现的多个子组件?
注意:我知道已经提出了类似的问题,但这有点不同.[ 如何使用React-Router更新基于URL /路径的ReactJS组件
假设我有类似下面的代码:一个配置文件页面(主布局视图),其中包含配置文件子部分的导航链接(设置,首选项,帐户详细信息等),以及一个主面板,其中每个子部分都被渲染.
所以目前我会有这样的东西:我的路由器 routes.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>
Run Code Online (Sandbox Code Playgroud)
以及我的配置文件布局组件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;
Run Code Online (Sandbox Code Playgroud)
所以这种作品.子组件将基于URL呈现.但那我该如何管理州和道具呢?我理解React和Flux的方式,我希望Profile组件管理状态并监听我的商店中的更改,并将这些更改传播给它的子项.它是否正确?
我的问题是似乎没有一种直观的方式将道具传递给this.props.children呈现的组件,这让我觉得我当前的架构和/或对通量的理解是不正确的.
非常感谢一点指导.
我觉得你所做的一切都很好。你走在正确的道路上。
React 为您提供了一组 API 组合,可以准确解决您不确定如何实现的问题 ( way to pass props to components rendered by this.props.children)
首先,你需要看一下cloneElement
它基本上会获取一个 React 元素,克隆它,然后返回另一个带有 props 的元素,您可以完全根据您的需要更改、更改或替换这些元素。
此外,将其与子实用程序结合起来- 循环遍历提供给顶级组件的子组件,并对每个元素单独进行必要的更改。
建议的示例用法可能很简单
<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>
Run Code Online (Sandbox Code Playgroud)
使用这些工具可以在任何地方创建真正通用且可重用的组件。更常用的实用程序Children是map、forEach和toArray。每个人都有自己各自的目标。
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
9065 次 |
| 最近记录: |