下面简单介绍一下泛型在 class component 与 functional component 里的运用
class components
interface IProps<T> {
name: string;
data: T[];
onChange?: (item: T) => void;
}
class Hello<T> extends React.Component<IProps<T>, any> {
render() {
return <div>hello</div>;
}
}
functional components
这有两种写法
use function
interface IProps<T> {
name: string;
data: T[];
onChange?: (item: T) => void;
}
function Hello<T>(props: IProps<T>) {
return <div>hello</div>;
}
use const
interface IProps<T> {
name: string;
data: T[];
onChange?: (item: T) => void;
}
const Hello = <T extends unknown>(props: IProps<T>) => {
return <div>hello</div>;
};
const Hello = <T>(props: IProps<T>) => {
return <div>hello</div>;
};
使用
const X = () => {
return <Hello name={} data={[1]} onChange={item => {
// item 会被自动推导成 number,与 data 类型关联。
console.log(item);
}} />;
}
以上。