有如下 2个react组件
export type DownFile = {
filename: string;
fileSize: number;
process: number;
};
const MapShow = () => {
const list: DownFile[] = [
{ filename: '下载任务一', fileSize: 100, process: 10 },
{ filename: '下载任务二', fileSize: 100, process: 10 },
{ filename: '下载任务三', fileSize: 100, process: 10 },
];
return (
<div>
<AMap />
<DownLoadList<DownFile>
dataSource={list}
/>
</div>
);
};
interface DownLoadListProps<T> {
dataSource: T[];
title?: string;
}
const DownLoadList = <T extends {}>({
title = '上传列表',
dataSource,
}: DownLoadListProps<T>) => {
const [visible, setVisible] = useState(true);
const column: ColumnProps<DownFile>[] = [
{ title: '文件名', key: 'filename', dataIndex: 'filename' },
{ title: '大小', key: 'fileSize', dataIndex: 'fileSize' },
{
title: '进度',
key: 'process',
dataIndex: 'process',
render: (value, record) => <Progress percent={record.process} size="small"/>,
},
{
title: '操作',
render: (value, record) => (
<>
<DeleteOutlined />
</>
),
},
];
return (
<Modal
title={title}
style={{ top: 20, right: 20 }}
visible={visible}
okText={'确认'}
cancelText={'取消'}
onOk={() => setVisible(false)}
onCancel={() => setVisible(false)}
>
<Table columns={column} dataSource={dataSource} />
</Modal>
);
};
在DownLoadList 组件中,无法推断初T的类型,导致typescript报错
这种形式的 范型组件 改如何 使用
在使用组件的地方,dataSource传值直接不带着类型应该就可以?ts应该可以根据你传给dataSource的值的类型自动将泛型变量替换为真正传递的值的类型