javascript - 如何在反应中有通用的打字稿道具?打字稿通用道具不起作用
问题描述
这就是我想要做的反应,
我有一个功能组件,我在其中传递了 1 个道具
<TableComponent tableStateProp={tableState} />
tableState 是父组件中的状态钩子
const [tableState, setTableState] = useState<TableState<string[]>>();
表状态类型是在我的表组件中定义的
export type TableState<T> = {
pagination: {
limit: number,
skip: number,
}
data: T[];
columns: string[],
}
但这是我的问题开始的地方,理想情况下我可以做到这一点
const TableComponent: React.FC<{
tableState: TableState<T>;
}> = ({tableState}) => {
但我得到一个错误说TS2304: Cannot find name 'T'.
我知道通用道具函数的语法类似于function<T>(): type<T>
但通用道具/对象是什么?
编辑:我在数据不是字符串 [] 的其他地方使用这个组件,因此我试图使其通用
谢谢
解决方案
你不需要使用React.FC<>
. 将您的组件声明为命名函数,您可以添加通用的<T>
.
export type TableState<T> = {
pagination: {
limit: number;
skip: number;
};
data: T[];
columns: string[];
};
function TableComponent<T>({
tableState,
}: React.PropsWithChildren<{
tableState: TableState<T>;
}>) {
// ...
}
如果您不需要children
道具工作,您也不需要使用React.PropsWithChildren
,只需:
function TableComponent<T>({ tableState }: { tableState: TableState<T> }) {
如果您想在TableComponent
级别上明确返回类型(而不是稍后在应用程序中使用它时),您可以查看React.FC
正在执行的操作并相应地明确输入:
function TableComponent<T>({
tableState,
}: {
tableState: TableState<T>;
}): ReactElement<any, any> | null {
return null;
}
推荐阅读
- archlinux - 如何使用 kickstart.cfg 虚拟安装 kvm Centos 8
- java - 查看绑定导致“指定的孩子已经有父母”
- sql-server - 如何在 SQL 中创建一个迭代器,它可以像在一组中一样对行进行计数?
- java - 在 Python 中运行包含 java 命令的批处理文件
- node.js - 无法通过 SSL 使用 node.js 连接到 postgres(协议不受支持)
- python - webscrypt 只有一个类的一部分?
- r - ggplot 手动标签,以字符为图标
- ffmpeg - 使用 FFmpeg 将 GIF 转换为 WEBM 时视频文件不完整
- python - 未找到带有参数 '('',)' 的 'anhangdelete' 的反向操作。尝试了 1 种模式:['Verwaltung/AnhangDelete/(?P
[0-9]+)$'] - java - 为什么 Spring Boot 库无法将其依赖项添加到父应用程序的类路径中?