关于renderChildren中的displayName问题

来源:6-6 日趋完美 - Menu 组件编码第三部分

EWL

2021-02-26

老师您好:
我的问题如下:

const renderChildren = () => {
        return React.Children.map(children, (child, index) => {
            const childElement = child as React.FunctionComponentElement<MenuItemProps>;
            // 这里直接取displayName不会报错,但是最终获取到的displayName为undefined,但是取name是ok的
            const { name } = childElement.type;

            if (name === 'MenuItem' || name === 'SubMenu') {
                return React.cloneElement(childElement, {
                    index: childElement.props.index ? childElement.props.index.toString() : index.toString()
                });
            } else {
                console.error("Warning: Menu has a child which is not a MenuItem component");
            }
        })
    }

然后我打印了一下type的类型,确认是function,但是还是通过直接读取childElement.type返回了一个有name属性的对象,且name的属性值确实是MenuItem,debug到这里着实有点不太明白了,希望老师指导一下,感谢~

写回答

2回答

张轩

2021-02-27

同学你好 首先我们的 childElement 不是之前说的 FunctionComponent 或者 称之为 FC,而是FunctionComponentElement 这两种类型是不同的 类型。

第一个是一个类似函数的数据结构,上面有一个属性 displayName,

第二个是这个组件的实例。我们来看一下他的类型文件

interface FunctionComponentElement<P> extends ReactElement<P, FunctionComponent<P>>

继承来自 ReactElement 再来看一下 ReactElement

interface ReactElement<P = any, T extends 很长> {
    type: T;
    props: P;
    key: Key | null;
}

可以看到 这个 type 就是我们传递过来的 FunctionComponent<MenuItemProps>

所以 type 其实就是组件函数本身。所以你在type 上面能取得组件函数的一系列属性

2
3
weixin_慕勒5362282
回复
张轩
感谢您的回复!
2022-02-19
共3条回复

EWL

提问者

2021-03-01

老师好,感谢您的回复哈。

0
0

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

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

2124 学习 · 959 问题

查看课程