2017-06-06 60 views
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>; 
    ... 
} 

回答

3

我能够做到这一点TS 2.3。重点是对该组件的“内部”和“外部”使用2种类型。

interface IProps<V> { 
    value: V; 
    doSomething(val: V): void; 
} 

// type "inside" component 
function _Comp<T>(props: IProps<T>) { 
    return <div />; 
} 

// type for "outside" of component 
interface GenericsSFC extends React.SFC<any> { 
    <T>(props: IProps<T> & { children?: React.ReactNode }, context?: any): JSX.Element; 
} 

const Comp = _Comp as GenericsSFC; 

// dont type check: v is of type "hey" 
<Comp value={"hey"} doSomething={v => v - 1} />; 
+0

似乎工作,只是很好奇,如果没有一些简单的方法..也'GenericsSFC'需要其内部组件类型IProps,所以可能最好也保持GenericSFC里面...... 可能是最好的可能只保留输入函数,并且根本不使用SFC:o – Jurosh

相关问题