gpt4 book ai didi

javascript - 动态设置 React 组件的 Props

转载 作者:行者123 更新时间:2023-11-28 05:13:40 25 4
gpt4 key购买 nike

我正在使用 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" ...一切正常,添加后我会得到以下信息:

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of RouterContext.

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of 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} />; };
}

关于javascript - 动态设置 React 组件的 Props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41164329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com