如何基于 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. Java泛型背后是什么?

    文Java中泛型的应用,让大家更好地理解泛型,以及常说的泛型类型擦除是什么概念,举一个简单的例子,如下: 这里可以看出来在代码编写阶段就已经报错了,不能往string类型的集合中添加int类型的数据. ...

  2. programmercarl——数组——二分查找

    二分查找,在经过: 34--https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-arr ...

  3. vue3.x全局$toast、$message、$loading等js插件

    有时候我们需要使用一些类似toast,messge.loading这些跟js交互很频繁的插件,vue3.x这类插件的定义跟vue2.x插件稍大,而且相对变得复杂了一点点. 第一种.需要时创建,用完移除 ...

  4. [Beta]the Agiles Scrum Meeting 7

    会议时间:2020.5.21 20:00 1.每个人的工作 今天已完成的工作 成员 已完成的工作 issue yjy 暂无 tq 新增功能:添加.选择.展示多个评测机,对新增功能进行测试 评测部分增加 ...

  5. 万维网www与HTTP协议

    文章转自:https://blog.csdn.net/weixin_43914604/article/details/105901440 学习课程:<2019王道考研计算机网络> 学习目的 ...

  6. reactnative实现qq聊天消息气泡拖拽消失效果

    前言(可跳过) 我在开发自己的APP时遇到了一个类似于qq聊天消息气泡拖拽消息的需求,因为在网上没有找到相关的组件,所以自己动手实现了一下 需求:对聊天消息气泡拖拽到一定长度松开时该气泡会消失(可自行 ...

  7. 从零开始的DIY智能家居 - 基于 ESP32 的智能浇水器

    前言 上次 土壤湿度传感器 完成之后,就立下一个 flag 要搭建一个智慧浇水的智能场景,现在终于有时间填坑了!(o゚▽゚)o 智慧浇水场景的核心设备有三个: 检测土壤状态的:土壤湿度传感器 通过这个 ...

  8. 进程间通信消息队列msgsnd执行:Invlid argument——万恶的经验主义

    最近在搞进程间通信,首先在我的ubuntu 14.04上写了接口和测试demo,编译和执行都OK,,代码如下: 接口文件ipcmsg.h /* ipcmsg.h */ #ifndef H_MSGIPC ...

  9. cf Make It Nondeterministic (简单贪心)

    有N个人.每个人都有两个名字. 给出这N个人的一个排列.p[1]...p[N]. 现在让每个人挑自己丙个名字中的一个名字.问是否存在一种方案,使得挑出来的N个名字按字典序排完以后正好是p[1]...p ...

  10. 非对称加密和linux上的 ssh-keygen 工具使用

    rsa :创造非对称加密的三个人名.原理是两个1024到2048之间的素数,以此为乘积.等... a*b=c  一般a*b为私钥端,c为公钥端.因为 c非常难算出a和b. ssh-keygen -t ...