解决 React.FC 错误类型

8 min read

报错

TS2322: Type '(props: OnlyWhenProps) => React.ReactNode' is not assignable to type 'FC<OnlyWhenProps>'.   Type 'ReactNode' is not assignable to type 'ReactElement<any, any> | null'.     Type 'undefined' is not assignable to type 'ReactElement<any, any> | null'.
const OnlyWhen:React.FC<OnlyWhenProps> =  (props:OnlyWhenProps ) => {
    const {when, children} = props;
    return when ? children : null;
}

解决

const OnlyWhen:React.FC<OnlyWhenProps> = (props: OnlyWhenProps) => {
    const { when,children,} = props;
    return when ? <>{children}</> : null;
};

延伸

React.FC是函数式组件,是在TypeScript使用的一个泛型,FC就是FunctionComponent的缩写,事实上React.FC可以写成React.FunctionComponent

React.FC 包含了 PropsWithChildren 的泛型,不用显式的声明 props.children 的类型。React.FC<> 对于返回类型是显式的,而普通函数版本是隐式的(否则需要附加注释)

React.FC提供了类型检查和自动完成的静态属性:displayName,propTypes和defaultProps(注意:defaultProps与React.FC结合使用会存在一些问题)

 interface FunctionComponent<P = {}> {
        (props: P, context?: any): ReactElement<any, any> | null;
        propTypes?: WeakValidationMap<P> | undefined;
        contextTypes?: ValidationMap<any> | undefined;
        defaultProps?: Partial<P> | undefined;
        displayName?: string | undefined;
    }

我们使用React.FC来写 React 组件的时候,是不能用setState的,取而代之的是useState()、useEffect等 Hook API