gpt4 book ai didi

javascript - 动态选择 React 组件并将数据应用为 props

转载 作者:行者123 更新时间:2023-11-28 14:10:49 27 4
gpt4 key购买 nike

我是 React 新手,我很确定这是可以完成的,但我不确定语法。

# pseudo code
const components = [
{component: <A />, type: "type_a"},
{component: <B />, type: "type_b"},
{component: <C />, type: "type_c"}
];

const Wrapper = ({type, data}) => {
const component = _.find(components, (c) => c.type === type);
return (
<component data={data} />
)
}

最佳答案

  const componentsArr = [
{component: A, type: "type_a"},
{component: B, type: "type_b"},
{component: C, type: "type_c"}
];

const Wrapper = ({type, data}) => {
const index = componentsArr.findIndex((c) => c.type === type);
if(index > -1) {
let DupComp = componentsArr[index].component;
return <DupComp data={data}/>
} else {
return (
<div>Not found this type</div>
)
}
}

关于javascript - 动态选择 React 组件并将数据应用为 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59561764/

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