组件prop的传入问题。

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

_沐雨

2020-06-11

图片描述
如图:第一行的写法,应该是表示这个方法返回内容是一个组件,其propsIDividerProps,这个没有疑问。
第二行,props是组件将接收到的,这种写法表示props是,PropsWithChildren的泛型参数传入了IDividerProps,为什么这种写法在使用组件的时候不能接收到IDividerProps的提示,他与第一行写法的不同是什么。
请老师答疑,谢谢!

写回答

1回答

张轩

2020-06-12

同学你好 

这两种写法有点画蛇添足,我们一般使用

const Hello: FC<HelloProps> = (props) => { return ...}

 来定义组件,这样 props 就会自动PropsWithChildren 属性。并且组件本身还会获得一系列的属性。

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

写法2 等于直接显式的指示了 props 的类型,为PropsWithChildren <Props> 这个其实就是给当前属性加一个 children 属性,没什么神奇的。

type PropsWithChildren<P> = P & { children?: ReactNode };

我在本地是可以直接获得提示的。不清楚你这里为什么没有提示,而且使用这种方式,要做到 Props 上面的属性都可选,否则就会报错。


0
0

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

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

2124 学习 · 959 问题

查看课程