Javascript 使用字符串中的道具渲染任何子组件
我需要能够调用容器组件并从字符串中呈现任何子组件列表 孩子们看起来都像这样:Javascript 使用字符串中的道具渲染任何子组件,javascript,reactjs,jsx,Javascript,Reactjs,Jsx,我需要能够调用容器组件并从字符串中呈现任何子组件列表 孩子们看起来都像这样: <ChildOne store={store} name="child-one" foo="bar" /> <ChildTwo store={store} name="child-two" foo="bar" /> <ChildThree store={store} name="child-three" foo="bar" /> const Container = props =&
<ChildOne store={store} name="child-one" foo="bar" />
<ChildTwo store={store} name="child-two" foo="bar" />
<ChildThree store={store} name="child-three" foo="bar" />
const Container = props => <section><some-variable store={store} name={props.name} foo={props.foo}></some-variable></section>
虽然我不确定如何用实际的组件替换某些变量
部分
编辑:试图澄清我的问题。我已经写了一个真实世界的例子,说明了我希望做什么才能使这项工作成功(但它不起作用,我想我很接近,下面的错误可能是一个愚蠢的错误造成的):
可以创建组件类和映射的数组
const容器=({组件:Comp,store,name})=>(
);
常数数据=[
[儿童一号,'儿童一号'],[儿童二号,'儿童二号'],[儿童三号,'儿童三号']
];
{data.map(([Comp,name])=>)}
您可以使用一些帮助程序来解决需要使用的组件。例如—
const components = new Map([
["first-child", FirstChildComponent],
["second-child", SecondChildComponent],
...etc.
]);
const getNecessaryComponent = (componentName = "some default value") => {
return components.get(componentName);
});
在您的容器中,您可以使用此函数解析需要使用的组件-
const Container = props => {
const Component = getNecessaryComponent(props.child);
return (
<section>
<Component
store={store}
name={props.name}
foo={props.foo}
></Component>
</section>
);
}
const Container=props=>{
const Component=getNecessaryComponent(props.child);
返回(
);
}
希望它对你有用 我让它工作了,答案是将
componentRegistry
更改为以下内容:
const componentRegistry = [
{
name: 'perception',
element: <Perception />
},
{
name: 'planned-status',
element: <PlannedStatus />
},
{
name: 'adjudication',
element: <Adjudication />
}
]
const componentRegistry=[
{
名称:'感知',
要素:
},
{
名称:“计划状态”,
要素:
},
{
名称:"裁决",,
要素:
}
]
老实说,你的问题太难理解了。是ChildOne
,ChildTwo
,ChildThree
是一些组件类是不同的。因此ChildOne
,ChildTwo
和ChildThree
都是可以插入父组件的不同组件,但是,每个组件都有完全相同的道具。
const Container = props => {
const Component = getNecessaryComponent(props.child);
return (
<section>
<Component
store={store}
name={props.name}
foo={props.foo}
></Component>
</section>
);
}
const componentRegistry = [
{
name: 'perception',
element: <Perception />
},
{
name: 'planned-status',
element: <PlannedStatus />
},
{
name: 'adjudication',
element: <Adjudication />
}
]