[英]Setting Props on React Component dynamically
我正在使用React,Redux和React-Router
我有这个routes.js
:
export default (
<Route path="/" component={App}>
<IndexRoute components={{ content: Home }} />
<Route path="clients" components={{ content: Clients, sidebar: wrapClientSidebarWithProps({sidebarSelectedName: 'all'}) }} />
</Route>
);
function wrapClientSidebarWithProps(props) {
return <ClientSidebar {...props} />;
}
您可以假设所有导入都在那里。 如果没有该<Route path="clients" ...
一切正常,添加后,我将得到以下信息:
警告:React.createElement:type不能为null,undefined,boolean或number。 它应该是一个字符串(对于DOM元素)或一个ReactClass(对于复合组件)。 检查
RouterContext
的渲染方法。未捕获的错误:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到了:对象。 检查
RouterContext
的渲染方法。
呈现这些内容的app.js
是:
const App = ({content, sidebar}) => {
let wholeSidebar;
if (sidebar) {
wholeSidebar = (
<section className="context-nav-container">
{sidebar}
</section>
);
}
return (
<div className="main-container">
<Header />
{content}
{wholeSidebar}
</div>
);
}
App.propTypes = {
content: PropTypes.object.isRequired,
sidebar: PropTypes.object
};
export default App;
ClientSideBar.js
是:
const ClientSidebar = ({selectedName}) => {
const linksObjs = [
{ id: 'all', name: 'All', to: 'clients', icon: 'fa-list' },
{ id: 'client', name: 'New', to: 'client', icon: 'fa-plus' }
];
const links = linksObjs.map((l, i) => {
const fullClasslist = 'fa ' + l.icon;
let stickClass = '';
if (l.id === selectedName) {
stickClass = 'stick';
}
return (
<li key={i} className={stickClass}><Link to={l.to}> <i className={fullClasslist} /> {l.name}</Link></li>
);
});
return (
<ul className="context-nav">
{links}
</ul>
);
};
ClientSidebar.propTypes = {
selectedName: PropTypes.string
};
export default ClientSidebar;
所以这个功能:
function wrapClientSidebarWithProps(props) {
return <ClientSidebar {...props} />;
}
无法返回创建的组件,它需要返回一个可以创建组件的函数:
function wrapClientSidebarWithProps(props) {
return function WrappedClientSidebar() { return <ClientSidebar {...props} />; };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.