React Typescript 功能组件语法错误
React Typescript Functional Component Syntax Error
我想创建一个通用功能组件,但我明白了 :
代码块;
interface IAppTable<Type> {
height: number;
data: Type[];
tableLayout: 'auto' | 'fixed';
pagination?: false;
}
const AppTable: <T>(props: IAppTable<T>) => React.FC<IAppTable<T>> = (props) => {
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const getColumns = () => {
setSelectedRows([1]);
return [];
};
return <></>;
}
正如@Shrey 所解释的,AppTable
不是 return 函数组件,它 是 一个函数组件。
React.FC
类型不支持通用组件。这不是问题,因为任何匹配 FC
签名的东西都可以用作 FC
。该签名是它需要一个道具对象和 return 一个 JSX.Element
。 FC
自动包含 children
道具,但我们可以使用助手 React.PropsWithChildren
自己添加它。
我们需要使函数本身通用,所以我们将类型应用于 props 和 return 而不是函数本身(这就是 React.FC
所做的,以及为什么它不能使用泛型)。
import React, { useState, PropsWithChildren } from "react";
const AppTable = <T extends any>(props: PropsWithChildren<IAppTable<T>>): JSX.Element => {
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const getColumns = () => {
setSelectedRows([1]);
return [];
};
return <></>;
}
我想创建一个通用功能组件,但我明白了
代码块;
interface IAppTable<Type> {
height: number;
data: Type[];
tableLayout: 'auto' | 'fixed';
pagination?: false;
}
const AppTable: <T>(props: IAppTable<T>) => React.FC<IAppTable<T>> = (props) => {
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const getColumns = () => {
setSelectedRows([1]);
return [];
};
return <></>;
}
正如@Shrey 所解释的,AppTable
不是 return 函数组件,它 是 一个函数组件。
React.FC
类型不支持通用组件。这不是问题,因为任何匹配 FC
签名的东西都可以用作 FC
。该签名是它需要一个道具对象和 return 一个 JSX.Element
。 FC
自动包含 children
道具,但我们可以使用助手 React.PropsWithChildren
自己添加它。
我们需要使函数本身通用,所以我们将类型应用于 props 和 return 而不是函数本身(这就是 React.FC
所做的,以及为什么它不能使用泛型)。
import React, { useState, PropsWithChildren } from "react";
const AppTable = <T extends any>(props: PropsWithChildren<IAppTable<T>>): JSX.Element => {
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const getColumns = () => {
setSelectedRows([1]);
return [];
};
return <></>;
}