【发布时间】:2021-05-26 09:33:43
【问题描述】:
对于一个项目,我想动态渲染不同的组件。 我将得到一个包含不同类型对象的数组,当我映射到该数组时,我想根据该对象的 prop 渲染一个组件。我可以使用 if/else || switch 语句,但是随着越来越多不同类型的对象,这些语句会很长,所以我想使用不同的方法,即使用 prop 作为对象的键,然后定义应该渲染的组件。
App.tsx
import instructions, { Instruction } from "./instructions";
import products, { Product } from "./products";
// COMPONENTS
interface ProductCompProps {
content: Product;
}
const ProductComponent: React.FC<ProductCompProps> = ({ content }) => {
return <h1>Product Component: {content.name}</h1>;
};
interface InstructionCompProps {
content: Instruction;
}
const InstructionComponent: React.FC<InstructionCompProps> = ({ content }) => {
return <h1>Product Component: {content.label}</h1>;
};
//
const datas = [...products, ...instructions];
interface Components {
[key: string]: React.FC<ProductCompProps> | React.FC<InstructionCompProps>;
}
const components: Components = {
ProductComponent,
InstructionComponent,
};
const App: React.FC = () => {
return (
<div>
{datas.map((data) => {
const Component = components[data.component];
return <Component content={data} />;
})}
</div>
);
};
export default App;
products.ts
export interface Product {
id: string;
name: string;
component: string;
}
const products: Product[] = [
{
id: "1",
name: "Product name One",
component: "ProductComponent",
},
{
id: "2",
name: "Product name Two",
component: "ProductComponent",
},
];
export default products;
instructions.ts
export interface Instruction {
id: string;
label: string;
component: string;
}
const instructions: Instruction[] = [
{
id: "1",
label: "Product name One",
component: "InstructionComponent",
},
{
id: "2",
label: "Product name Two",
component: "InstructionComponent",
},
];
export default instructions;
所以这个自定义组件“组件”可以是 X 组件之一,每个组件都有自己的 props。
但是 Typescript 给我的 content prop 出现以下错误:
Type 'Product | Instruction' is not assignable to type 'Product & Instruction'.
Type 'Product' is not assignable to type 'Product & Instruction'.
我的理解是,您只能索引具有某些类型的对象,例如字符串或数字。 在我设置字符串键的情况下:
interface Components {
[key: string]: React.FC<ProductCompProps> | React.FC<InstructionCompProps>;
}
索引正在工作,但是我不明白为什么编译器会混合组件属性的类型...
我会非常感谢任何帮助。请理解,我对 typescript 很陌生,所以我仍然在为泛型和高级 typescript 的东西而苦恼。
【问题讨论】:
-
如果每个对象的类型都是随机的,为什么不
any输入?
标签: reactjs typescript