react 根据接口返回结果(结果是一个数组,包含不同组件名)加载相应的组件,同时每个组件调用相应的接口去获得数据(但是组件内不能写接口,只能传参),请问这种情况如何实现
react 根据接口返回结果加载相应的组件,同时每个组件调用相应的接口去获得数据(但是组件内不能写接口,只能传参)
oyb81076
#5
import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";
import ComponentC from "./ComponentC";
const ApiComponents = {
ComponentA, ComponentB, ComponentC
}
function Item({component, args}){
const Component = ApiComponents[component];
if (!Component) { return <>组件{component}不存在</> }
return <Component {...args} />
}
function App(){
const data = [
{component: "ComponentA", args: {id: 1, nickname: 2}},
{component: "ComponentB", args: {title: "xxxxx"},
];
return (
<>
{data.map((x, i)=> <Item key={i} {...x} /> )}
</>
);
}
不过个人不是很建议这么搞, 更加建议使用这种, 代码易读性更好
import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";
function Item({data}){
switch(data.type){
case "PersonData": return <ComponentA id={data.args.id} nickname={data.args.nickname} />;
case "UserTitle": return <ComponentA title={data.args.title} />;
default: return <>参数type:${data.type}错误</>
}
}
function App(){
const data = [
{type: "PersonData", args: {id: 1, nickname: 2}},
{type: "UserTitle", args: {title: "xxxxx"},
];
return (
<>
{data.map((x, i)=> <Item key={i} data={x} /> )}
</>
);
}