如何在TypeScript中向通用React组件动态传递接口/类型
解决React+TypeScript通用表格组件的类型适配问题
你的问题出在当前的Table组件硬编码了固定的数据类型,只能接受结构为{name: string; age: number}的数据数组,自然无法适配Product页面的不同数据结构。要做通用表格组件,得把它改成泛型组件,让它能兼容任意类型的数据,同时补充列配置来定义不同数据的渲染规则。
修改后的Table.tsx(泛型组件实现)
import React from 'react'; // 列配置类型:定义每列的标题、对应数据字段、可选自定义渲染逻辑 interface ColumnConfig<T> { title: string; // keyof T 确保字段名一定存在于数据类型T中,避免拼写错误 field: keyof T; render?: (value: T[keyof T], item: T) => React.ReactNode; } // 组件Props:使用泛型T表示数据项的类型 interface TableProps<T> { data: T[]; columns: ColumnConfig<T>[]; } // 泛型组件,T extends object 限制数据为对象类型 function Table<T extends object>({ data, columns }: TableProps<T>) { return ( <table border="1" cellSpacing="0" cellPadding="8"> <thead> <tr> {columns.map((col, idx) => ( <th key={idx}>{col.title}</th> ))} </tr> </thead> <tbody> {data.map((item, rowIdx) => ( <tr key={rowIdx}> {columns.map((col, colIdx) => { const value = item[col.field]; return ( <td key={colIdx}> {/* 优先使用自定义渲染,否则直接显示值 */} {col.render ? col.render(value, item) : value} </td> ); })} </tr> ))} </tbody> </table> ); } export default Table;
User.tsx 适配修改后的组件
import Table from "./Table"; interface InterfaceUser { name: string; age: number; } const users: InterfaceUser[] = [ { name: "John", age: 21 }, { name: "Alice", age: 25 } ]; function User() { // 定义用户表格的列规则 const columns = [ { title: "姓名", field: "name" }, { title: "年龄", field: "age" } ]; return <Table data={users} columns={columns} />; } export default User;
Product.tsx 适配修改后的组件(同时修正原代码的类型错误)
原代码里InterfaceProduct定义了age但数据里用的是price,这里先统一类型:
import Table from "./Table"; interface InterfaceProduct { title: string; price: number; } const products: InterfaceProduct[] = [ { title: "Product name", price: 21 }, { title: "Wireless Headset", price: 99 } ]; function Product() { // 定义商品表格的列规则,还可以给价格加自定义格式化 const columns = [ { title: "商品名称", field: "title" }, { title: "价格", field: "price", render: (price) => `$${price.toFixed(2)}` } ]; return <Table data={products} columns={columns} />; } export default Product;
关键说明
- 泛型T:让组件可以接受任意对象类型的数据,不用写死固定接口,实现真正的通用性。
- keyof T:确保列配置的
field一定是数据类型T中存在的字段,编译阶段就能拦截拼写错误。 - 自定义render函数:灵活处理不同字段的显示需求,比如格式化价格、日期,或者渲染按钮等交互元素。
内容的提问来源于stack exchange,提问作者Vineet Kumar
相关产品推荐
相关产品推荐

