前端组件库| 青训营笔记

88 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 14 天

在开发组件库的过程中,自己模拟实现了一个布局组件。

布局组件顾名思义,帮助使用者来构建布局,参照antd,我也用flex布局来实现了布局组件

效果

d43c6e7efe592110dc56366021b0b4e.png 文档站的效果

知识

flex布局

关于flex常用的属性,我们可以划分为容器属性和容器成员属性

容器属性有:

  • flex-direction
  • flex-wrap
  • flex-flow
  • justify-content
  • align-items
  • align-content

容器成员属性如下:

  • order
  • flex-grow
  • flex-shrink
  • flex-basis
  • flex
  • align-self

思路

主要利用flex布局,注意嵌套问题即可。

对于Layout组件

  • 对于没有嵌套的情况,就是只有一层layout
  • -比如说上中下三栏布局,可以设置flex主轴方向纵向,使得只需要分配各自的高度就可以填充页面
  • -比如说左右布局,主要是加入了sider,可以加入判定,有sider的时候设置flex 主轴方向横向
  • 对于有嵌套的情况,设置内层主轴横向即可,方便内层嵌套sider

实现

样式

.Layout-row {
  display: flex;
  flex-direction: row;

  &>.content {
    flex: 1;
  }

  &>.Layout-column {
    flex: 1;
  }
}

.Layout-column {
  display: flex;
  flex-direction: column;
}

.layout-test{
  display: flex;
  flex-direction:row;
  
  &>li{
    list-style: none;
    flex:1;
  }
}

逻辑

import React, { FC } from 'react';
interface BaseLayoutProps {
  children?: React.ReactNode;
  style?: any; //todo react中css样式对象定义
}

export type LayoutProps = Partial<BaseLayoutProps>;

//部分,都有公共的定义BaseLayoutProps,里面可能会有各种子组件;同时利用解构赋值,把其余属性赋予
const Header: FC<BaseLayoutProps> = ({ children, ...props }) => {
  return <div {...props}>{children}</div>;
};
const Content: FC<BaseLayoutProps> = ({ children, ...props }) => {
  return (
    <div className="content" {...props}>
      {children}
    </div>
  );
};
const Sider: FC<BaseLayoutProps> = ({ children, ...props }) => {
  return <div {...props}>{children}</div>;
};
const Footer: FC<BaseLayoutProps> = ({ children, ...props }) => {
  return <div {...props}>{children}</div>;
};
//主体
const Layout: FC<LayoutProps> = ({ children, ...props }) => {
  // debugger;
  // console.log(children);
  // let contents:any[]=children
  if (children !== undefined && children !== null&&children instanceof Array) {
    for (let i = 0; i < children.length; i++) {
      if ((children[i] as any).type.name === 'Sider') {
        //有侧边栏,则flex主轴方向水平
        return (
          <div className="Layout-row" {...props}>
            {children}
          </div>
        );
      }
    }
  }

  return (
    <div className="Layout-column" {...props}>
      {children}
    </div>
  ); //没有则竖直
};

Layout.defaultProps = {
  children: [],
};

export { Layout, Header, Sider, Content, Footer };

flex布局部分参考vue3js.cn/interview/c…