老师好 关于React.FC<BaseButtonProps>

来源:4-8 小试牛刀 - Button 组件编码 第一部分

袁门弟子

2020-06-20

老师好,关于:

React.FC<BaseButtonProps>

这里的BaseButtonProps是对props的类型注解嘛?

我之前如果要用泛型,感觉一般是<T extends BaseButtonProps> = (props: T) => {.....}

这样来写的,请问老师,我这样写对吗?有点蒙圈

写回答

1回答

张轩

2020-06-20

同学你好 之前我们说过 泛型可以在 interface 中使用,这里就是一个例子,可以点进去研究一下 FC 的定义。

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

这个 P 就是传入的 props,其实它最终生成的一个类型就是一个混合类型,主体是一个函数,参数是 props 不仅有BaseButtonProps 还多了 children。

这个函数上面还有静态属性 propTypes,contextTypes 等等。

也就是说,我们声明一个变量为 React.FC<BaseButtonProps>类型的时候 ,它就能获得这么丰富的类型帮助,从另外一个侧面也能感受到 interface 这个 duck typing 的妙用。

0
2
Lucky雷
按照视频编码出现这个报错 Type '{ (props: BaseButtonProps): Element | undefined; defaultProps: Partial | undefined; }' is not assignable to type 'FC'. Type 'Element | undefined' is not assignable to type 'ReactElement | null'. Type 'undefined' is not assignable to type 'ReactElement | null'.
2022-09-11
共2条回复

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2123 学习 · 959 问题

查看课程