SEMI DESIGN 源码学习(四)间距

1,255 阅读1分钟

今天看一个比较简单的组件 Space,它用来设置组件之间的间距。源码位于 packages/semi-ui/space/index.tsx

image.png

Space 的属性用的都是 type 关键字

image.png

渲染的时候使用 flatten 函数处理子元素

image.png

flatten 函数使用递归的方式判断传入的 children 元素,感觉这方法效率应该不高 (ˇˍˇ)~

export const flatten = (children: ReactNode): Array<ReactNode> => {
    let res: Array<ReactNode> = [];

    React.Children.forEach(children, child => {
        if (child === undefined || child === null) {
            return;
        }
        if (Array.isArray(child)) {
            res = res.concat(flatten(child));
        } else if (isValidElement(child) && child.type && child.type.toString() === REACT_FRAGMENT_TYPE && child.props) {
            res = res.concat(flatten(child.props.children));
        } else {
            res.push(child);
        }
    });
    return res;
};

至此看完,简单的一个组件,主要内容在于判断传给组件的属性,然后添加对应的样式。