2
如何定义通用类型基于参数或外部配置的React无状态组件?Typescript具有通用参数/返回类型的React无状态函数
实施例组分:
interface IProps<V> {
value: V;
doSomething: (val: V) => void;
}
const Comp: React.SFC<IProps<number>> = <T extends number>({
value: T,
doSomething
}) => {
return <div />;
}
以上示例将工作,而只用数字作为值。
是可以做到的升级来实现类似:
const Comp: React.SFC<IProps<??>> = <?? extends string | number>({
value, /* of type ?? */
doSomething
}) => {
return <div />;
}
这样我们就可以决定,无论我们使用组件时需要数字或字符串。
所需的使用:
// This should setup generic type to string
<Comp value="string" ... />
// Or number
<Comp value={123} ... />
// Should be compilation error as we cannot use * on 'text' * 5
<Comp value="text" doSomething={val => val * 5} />
编辑:应该做同样的工作function
做:
function Comp <T>({value, doSomething}: IProps<T>) { ... }
SFC类型有定义:
interface SFC<P> {
(props: P & { children?: ReactNode }, context?: any): ReactElement<any>;
...
}
似乎工作,只是很好奇,如果没有一些简单的方法..也'GenericsSFC'需要其内部组件类型IProps,所以可能最好也保持GenericSFC里面...... 可能是最好的可能只保留输入函数,并且根本不使用SFC:o – Jurosh