[英]How to pass interface/type dynamically to a common react function in typescript
I have created a common function to render a table.我创建了一个通用函数来呈现表格。
Table.tsx表.tsx
interface Type {
name: string;
age: number;
}
interface PropType {
column: Array<Type>;
}
function Table({ column }: PropType) {
return null;
}
export default Table;
Now I am using this component for two different pages, User and Product.现在我将这个组件用于两个不同的页面,用户和产品。 both user and product page has different data to be rendered on table component
用户和产品页面都有不同的数据要在表组件上呈现
User.tsx用户.tsx
import Table from "./Table";
interface InterfaceUser {
name: string;
age: number;
}
const users: Array<InterfaceUser> = [
{
name: "John",
age: 21
}
];
function User() {
return <Table column={users} />;
}
export default User;
User.tsx works well as we have created the same interface in table component but when it comes to Product.tsx page, we get errors. User.tsx 运行良好,因为我们在表组件中创建了相同的界面,但是当涉及到 Product.tsx 页面时,我们会遇到错误。
import Table from "./Table";
interface InterfaceProduct {
title: string;
age: number;
}
const products: Array<InterfaceProduct> = [
{
title: "Product name",
price: 21
}
];
function Product() {
return <Table column={products} />;
}
export default Product;
I am new to typescript, any help would really be appreciated.我是打字稿的新手,非常感谢任何帮助。
You can use Typescript generic type like this:您可以像这样使用 Typescript 通用类型:
In Table.tsx
:在
Table.tsx
:
interface PropType<ColumnsType> {
column: ColumnsType[];
}
function Table<ColumnType>({ column }: PropType<ColumnType>) {
return null;
}
in User.tsx
:在
User.tsx
中:
function User() {
return <Table<InterfaceUser> column={users} />;
}
in Product.tsx
:在
Product.tsx
中:
function Product() {
return <Table<InterfaceProduct> column={products} />;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.