如何基于 React 封装一个组件

前言

很多小伙伴在第一次尝试封装组件时会和我一样碰到许多问题,比如人家的组件会有 color 属性,我们在使用组件时传入组件文档中说明的属性值如 primary ,那么这个组件的字体颜色会变为 primary 对应的颜色,这是如何做到的?还有别人封装的组件类名都有自己独特的前缀,这是如何处理的呢,难道是 css 类名全部加上前缀吗,这也太麻烦了!

如果你正在困惑这些问题,你可以看看这篇文章。

我会参照 antd的divider组件 来讲述如何基于React封装一个组件,以及解答上述的一些问题,请耐心看完!

antd 是如何封装组件的

仓库地址

divider 组件源代码

antd 的源码使用了 TypeScript 语法,因此不了解语法的同学要及时了解哦!

import * as React from 'react';
import classNames from 'classnames';
import { ConfigConsumer, ConfigConsumerProps } from '../config-provider'; export interface DividerProps {
prefixCls?: string;
type?: 'horizontal' | 'vertical';
orientation?: 'left' | 'right' | 'center';
className?: string;
children?: React.ReactNode;
dashed?: boolean;
style?: React.CSSProperties;
plain?: boolean;
} const Divider: React.FC<DividerProps> = props => (
<ConfigConsumer>
{({ getPrefixCls, direction }: ConfigConsumerProps) => {
const {
prefixCls: customizePrefixCls,
type = 'horizontal',
orientation = 'center',
className,
children,
dashed,
plain,
...restProps
} = props;
const prefixCls = getPrefixCls('divider', customizePrefixCls);
const orientationPrefix = orientation.length > 0 ? `-${orientation}` : orientation;
const hasChildren = !!children;
const classString = classNames(
prefixCls,
`${prefixCls}-${type}`,
{
[`${prefixCls}-with-text`]: hasChildren,
[`${prefixCls}-with-text${orientationPrefix}`]: hasChildren,
[`${prefixCls}-dashed`]: !!dashed,
[`${prefixCls}-plain`]: !!plain,
[`${prefixCls}-rtl`]: direction === 'rtl',
},
className,
);
return (
<div className={classString} {...restProps} role="separator">
{children && <span className={`${prefixCls}-inner-text`}>{children}</span>}
</div>
);
}}
</ConfigConsumer>
); export default Divider;

如何暴露组件属性

在源码中,最先看到的是以下内容,这些属性也就是divider组件所暴露的属性,我们可以 <Divider type='vertical' /> 这样来传入 type 属性,那么 divider 分割线样式就会渲染为垂直分割线,是不是很熟悉!

export interface DividerProps { // interface 是 TypeScript 的语法
prefixCls?: string;
type?: 'horizontal' | 'vertical'; // 限定 type 只能传入两个值中的一个
orientation?: 'left' | 'right' | 'center';
className?: string;
children?: React.ReactNode;
dashed?: boolean;
style?: React.CSSProperties;
plain?: boolean;
}

在上面的属性中,我们还发现 className 和 style是比较常见的属性,这代表我们可以 <Divider type='vertical' className='myClassName' style={{width: '1em'}} /> 这样使用这些属性。

如何设置统一类名前缀

我们知道,antd 的组件类名会有他们独特的前缀 ant-,这是如何处理的呢?继续看源码。

<ConfigConsumer>
{({ getPrefixCls, direction }: ConfigConsumerProps) => {
const {
prefixCls: customizePrefixCls,
type = 'horizontal',
orientation = 'center',
className,
children,
dashed,
plain,
...restProps
} = props;
const prefixCls = getPrefixCls('divider', customizePrefixCls);

从源码中,我们发现 prefixCls ,这里是通过 getPrefixCls 方法生成,再看看 getPrefixCls 方法的源码,如下。

export interface ConfigConsumerProps {
...
getPrefixCls: (suffixCls?: string, customizePrefixCls?: string) => string;
...
} const defaultGetPrefixCls = (suffixCls?: string, customizePrefixCls?: string) => {
if (customizePrefixCls) return customizePrefixCls; return suffixCls ? `ant-${suffixCls}` : 'ant';
};

不难发现此时会生成的类名前缀为 ant-divider

如何处理样式与类名

我们封装的组件肯定是有预设的样式,又因为样式要通过类名来定义,而我们传入的属性值则会决定组件上要添加哪个类名,这又是如何实现的呢?下面看源码。

import classNames from 'classnames';

const classString = classNames(
prefixCls,
`${prefixCls}-${type}`,
{
[`${prefixCls}-with-text`]: hasChildren,
[`${prefixCls}-with-text${orientationPrefix}`]: hasChildren,
[`${prefixCls}-dashed`]: !!dashed,
[`${prefixCls}-plain`]: !!plain,
[`${prefixCls}-rtl`]: direction === 'rtl',
},
className,
);
return (
<div className={classString} {...restProps} role="separator">
{children && <span className={`${prefixCls}-inner-text`}>{children}</span>}
</div>
);

我们发现,它通过 classNames 方法(classNames是React处理多类名的组件)定义了一个所有类名的常量,然后传给了 div 中的 className 属性。

其实生成的类名也就是 ant-divider-horizontal 这个样子,那么css中以此类名定义的样式也就自然会生效了。而 className 和 style 属性则是通过 {...restProps} 来传入。

最后我们再看看它的css样式代码是怎么写的!

divider 组件样式源代码

antd 组件的样式使用 Less 书写,不了解 Less 语法的同学一定要了解一下。

@import '../../style/themes/index';
@import '../../style/mixins/index'; @divider-prefix-cls: ~'@{ant-prefix}-divider'; // 可以看到这里对应的也就是之前说到的类名前缀 .@{divider-prefix-cls} {
.reset-component(); border-top: @border-width-base solid @divider-color; &-vertical { // 这里的完整类名其实就是 ant-divider-vertical, 也就是 divider 组件的 type 属性值为 vertical 时对应的样式
position: relative;
top: -0.06em;
display: inline-block;
height: 0.9em;
margin: 0 8px;
vertical-align: middle;
border-top: 0;
border-left: @border-width-base solid @divider-color;
} &-horizontal {
display: flex;
clear: both;
width: 100%;
min-width: 100%;
margin: 24px 0;
} &-horizontal&-with-text {
display: flex;
margin: 16px 0;
color: @heading-color;
font-weight: 500;
font-size: @font-size-lg;
white-space: nowrap;
text-align: center;
border-top: 0;
border-top-color: @divider-color; &::before,
&::after {
position: relative;
top: 50%;
width: 50%;
border-top: @border-width-base solid transparent;
// Chrome not accept `inherit` in `border-top`
border-top-color: inherit;
border-bottom: 0;
transform: translateY(50%);
content: '';
}
} &-horizontal&-with-text-left {
&::before {
top: 50%;
width: @divider-orientation-margin;
} &::after {
top: 50%;
width: 100% - @divider-orientation-margin;
}
} &-horizontal&-with-text-right {
&::before {
top: 50%;
width: 100% - @divider-orientation-margin;
} &::after {
top: 50%;
width: @divider-orientation-margin;
}
} &-inner-text {
display: inline-block;
padding: 0 @divider-text-padding;
} &-dashed {
background: none;
border-color: @divider-color;
border-style: dashed;
border-width: @border-width-base 0 0;
} &-horizontal&-with-text&-dashed {
border-top: 0; &::before,
&::after {
border-style: dashed none none;
}
} &-vertical&-dashed {
border-width: 0 0 0 @border-width-base;
} &-plain&-with-text {
color: @text-color;
font-weight: normal;
font-size: @font-size-base;
}
} @import './rtl';

这样一来,我相信同学们也大概了解如何去封装一个组件以及关键点了,在源码中还有很多地方值得我们学习,比如这里的 ConfigConsumer 的定义与使用,感兴趣的同学欢迎一起交流。

笔记下载

此文章系原创,转载请附上链接,抱拳。

此文档提供 markdown 源文件下载,请去我的码云仓库进行下载。 下载文档

若本文对你有用,请不要忘记给我的点个 Star 哦!

如何基于 React 封装一个组件的更多相关文章

  1. 基于 React 封装的高德地图组件,帮助你轻松的接入地图到 React 项目中。

    react-amap 这是一个基于 React 封装的高德地图组件,帮助你轻松的接入地图到 React 项目中. 文档实例预览: Github Web | Gitee Web 特性 ️ 自动加载高德地 ...

  2. 基于 React 实现一个 Transition 过渡动画组件

    过渡动画使 UI 更富有表现力并且易于使用.如何使用 React 快速的实现一个 Transition 过渡动画组件? 基本实现 实现一个基础的 CSS 过渡动画组件,通过切换 CSS 样式实现简单的 ...

  3. 基于 element-plus 封装一个依赖 json 动态渲染的查询控件

    前情回顾 基于 el-form 封装一个依赖 json 动态渲染的表单控件 Vue3 封装第三方组件(一)做一个合格的传声筒 功能 使用 vue3 + element-plus 封装了一个查询控件,专 ...

  4. Vue.use源码分析(转)+如何封装一个组件

    封装一个组件:https://www.jianshu.com/p/89a05706917a 我想有过vue开发经验的,对于vue.use并不陌生.当使用vue-resource或vue-router等 ...

  5. 基于iview 封装一个vue 表格分页组件

    iview 是一个支持中大型项目的后台管理系统ui组件库,相对于一个后台管理系统的表格来说分页十分常见的 iview是一个基于vue的ui组件库,其中的iview-admin是一个已经为我们搭好的后天 ...

  6. 基于better-scroll封装一个上拉加载下拉刷新组件

    1.起因 上拉加载和下拉刷新在移动端项目中是很常见的需求,遂自己便基于better-scroll封装了一个下拉刷新上拉加载组件. 2.过程 better-scroll是目前比较好用的开源滚动库,提供很 ...

  7. 基于react hooks,zarm组件库配置开发h5表单页面

    最近使用React Hooks结合zarm组件库,基于js对象配置方式开发了大量的h5表单页面.大家都知道h5表单功能无非就是表单数据的收集,验证,提交,回显编辑,通常排列方式也是自上向下一行一列的方 ...

  8. 基于highcharts封装的组件-demo&源码

    前段时间做的项目中需要用到highcharts绘制各种图表,其实绘制图表本身代码很简单,但是由于需求很多,有大量的图形需要绘制,所以就不得不复制粘贴大量重复(默认配置等等)的代码,所以,后来抽空自己基 ...

  9. 基于 el-form 封装一个依赖 json 动态渲染的表单控件

    nf-form 表单控件的功能 基于 el-form 封装了一个表单控件,包括表单的子控件. 既然要封装,那么就要完善一些,把能想到的功能都要实现出来,不想留遗憾. 毕竟UI库提供的功能都很强大了,不 ...

随机推荐

  1. 2020.3.21--ICPC训练联盟周赛Benelux Algorithm Programming Contest 2019

    A Appeal to the Audience 要想使得总和最大,就要使最大值被计算的次数最多.要想某个数被计算的多,就要使得它经过尽量多的节点.于是我们的目标就是找到 k 条从长到短的链,这些链互 ...

  2. 对epoll机制的学习理解v1

    epoll机制 wrk用非阻塞多路复用IO技术创造出大量的连接,从而达到很好的压力测试效果.epoll就是实现IO多路复用的关键. 本节是对epoll的本质的学习总结,进一步的参考资料为: <深 ...

  3. Unity——EasyTouch摇杆插件使用

    EasyTouch摇杆插件使用 Demo展示 双指缩放在电脑端无法掩饰,竖屏将就看看吧: 插件名叫EasyTouch,有需要给我留言,不想开仓库传了: 创建摇杆点这里: 初始化 On_Joystick ...

  4. 【c++ Prime 学习笔记】第16章 模板与泛型编程

    面向对象编程(OOP)和泛型编程(GP)都能处理在编写程序时类型未知的情况 OOP能处理运行时获取类型的情况 GP能处理编译期可获取类型的情况 标准库的容器.迭代器.算法都是泛型编程 编写泛型程序时独 ...

  5. Takin Talks·上海 |开源后首场主题研讨会来了,一起解密Takin技术吧!

      自 6 月 25 日全球首款生产环境全链路压测平台 Takin 正式开源,短短 13 天时间,Github 主页上 Star 数已超过 730,开发者社群也积累了 1500+粉丝.群内技术研讨氛围 ...

  6. BPMN 學習實例

    什麼是業務流程圖? What is BPMN 業務流程建模符號(BPMN)是業務流程建模的一種方法.它基於統一建模語言(UML)中活動圖的概念,以圖形符號(業務流程圖)支持業務流程的規範.BPMN為企 ...

  7. [软工顶级理解组] Alpha阶段项目展示

    目录 团队成员 软件介绍 项目简介 预期典型用户 功能描述 预期目标用户数 用户反馈 团队管理 分工协作 项目管理 取舍平衡 代码管理 程序测试 代码规范 文档撰写 继续开发指导性 用户沟通 需求分析 ...

  8. Vulnstack内网靶场3

    Vulnstack内网靶场3 (qiyuanxuetang.net) 环境配置 打开虚拟机镜像为挂起状态,第一时间进行快照,部分服务未做自启,重启后无法自动运行. 挂起状态,账号已默认登陆,cento ...

  9. 最短路spaf及dijkstra模板

    spaf的双端队列优化: #include<bits/stdc++.h> #define ll long long const ll maxn=210000; using namespac ...

  10. hdu 1058 Humble Numbers(构造?枚举?)

    题意: 一个数的质因子如果只是2,3,5,7中的若干个.则这个数叫做humble number. 例如:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 1 ...