網站首頁 編程語言 正文
前言
很多小伙伴在第一次嘗試封裝組件時會和我一樣碰到許多問題,比如人家的組件會有 color 屬性,我們在使用組件時傳入組件文檔中說明的屬性值如 primary ,那么這個組件的字體顏色會變為 primary 對應的顏色,這是如何做到的?還有別人封裝的組件類名都有自己獨特的前綴,這是如何處理的呢,難道是 css 類名全部加上前綴嗎,這也太麻煩了!
如果你正在困惑這些問題,你可以看看這篇文章。
我會參照?antd的divider組件?來講述如何基于React封裝一個組件,以及解答上述的一些問題,請耐心看完!
antd 是如何封裝組件的
倉庫地址
- divider 組件在下圖對應目錄下 (代碼我會拷貝過來,感興趣的還是可以去克隆一下倉庫)
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 方法)定義了一個所有類名的常量,然后傳給了 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 的定義與使用,感興趣的同學歡迎一起交流。
總結
原文鏈接:https://www.cnblogs.com/guying-blog/p/15612611.html
相關推薦
- 2022-05-15 C++?Clock類模擬實現鬧鐘運行_C 語言
- 2022-12-10 Android入門之計時器Chronometer的使用教程_Android
- 2022-11-24 redis使用skiplist跳表的原因解析_Redis
- 2022-01-12 2022年了--你還不會手寫promise? --_-- promise的實現 第一版
- 2022-04-08 Python編程-封裝,繼承與多態_python
- 2023-09-18 子組件向父組件傳值的4種方法
- 2022-04-19 基于HarmonyOS 的ArkUI編寫的社區類app(一)----隱私服務條款界面
- 2023-04-07 React?Fiber構建源碼解析_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支