基于React封裝組件的實(shí)現(xiàn)步驟
前言
很多小伙伴在第一次嘗試封裝組件時(shí)會(huì)和我一樣碰到許多問題,比如人家的組件會(huì)有 color 屬性,我們在使用組件時(shí)傳入組件文檔中說明的屬性值如 primary ,那么這個(gè)組件的字體顏色會(huì)變?yōu)?primary 對應(yīng)的顏色,這是如何做到的?還有別人封裝的組件類名都有自己獨(dú)特的前綴,這是如何處理的呢,難道是 css 類名全部加上前綴嗎,這也太麻煩了!
如果你正在困惑這些問題,你可以看看這篇文章。
我會(huì)參照 antd的divider組件 來講述如何基于React封裝一個(gè)組件,以及解答上述的一些問題,請耐心看完!
antd 是如何封裝組件的
倉庫地址
- antd 倉庫地址:https://github.com/ant-design/ant-design
- divider 組件在下圖對應(yīng)目錄下 (代碼我會(huì)拷貝過來,感興趣的還是可以去克隆一下倉庫)
divider 組件源代碼
antd 的源碼使用了 TypeScript 語法,因此不了解語法的同學(xué)要及時(shí)了解哦!
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;
如何暴露組件屬性
在源碼中,最先看到的是以下內(nèi)容,這些屬性也就是divider組件所暴露的屬性,我們可以 <Divider type='vertical' />
這樣來傳入 type 屬性,那么 divider 分割線樣式就會(huì)渲染為垂直分割線,是不是很熟悉!
export interface DividerProps { // interface 是 TypeScript 的語法 prefixCls?: string; type?: 'horizontal' | 'vertical'; // 限定 type 只能傳入兩個(gè)值中的一個(gè) orientation?: 'left' | 'right' | 'center'; className?: string; children?: React.ReactNode; dashed?: boolean; style?: React.CSSProperties; plain?: boolean; }
在上面的屬性中,我們還發(fā)現(xiàn) className 和 style是比較常見的屬性,這代表我們可以 <Divider type='vertical' className='myClassName' style={{width: '1em'}} />
這樣使用這些屬性。
如何設(shè)置統(tǒng)一類名前綴
我們知道,antd 的組件類名會(huì)有他們獨(dú)特的前綴 ant-
,這是如何處理的呢?繼續(xù)看源碼。
<ConfigConsumer> {({ getPrefixCls, direction }: ConfigConsumerProps) => { const { prefixCls: customizePrefixCls, type = 'horizontal', orientation = 'center', className, children, dashed, plain, ...restProps } = props; const prefixCls = getPrefixCls('divider', customizePrefixCls);
從源碼中,我們發(fā)現(xiàn) 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'; };
不難發(fā)現(xiàn)此時(shí)會(huì)生成的類名前綴為 ant-divider
。
如何處理樣式與類名
我們封裝的組件肯定是有預(yù)設(shè)的樣式,又因?yàn)闃邮揭ㄟ^類名來定義,而我們傳入的屬性值則會(huì)決定組件上要添加哪個(gè)類名,這又是如何實(shí)現(xiàn)的呢?下面看源碼。
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> );
我們發(fā)現(xiàn),它通過 classNames 方法(classNames是React處理多類名的組件)定義了一個(gè)所有類名的常量,然后傳給了 div 中的 className 屬性。
其實(shí)生成的類名也就是 ant-divider-horizontal
這個(gè)樣子,那么css中以此類名定義的樣式也就自然會(huì)生效了。而 className 和 style 屬性則是通過 {...restProps}
來傳入。
最后我們再看看它的css樣式代碼是怎么寫的!
divider 組件樣式源代碼
antd 組件的樣式使用 Less 書寫,不了解 Less 語法的同學(xué)一定要了解一下。
@import '../../style/themes/index'; @import '../../style/mixins/index'; @divider-prefix-cls: ~'@{ant-prefix}-divider'; // 可以看到這里對應(yīng)的也就是之前說到的類名前綴 .@{divider-prefix-cls} { .reset-component(); border-top: @border-width-base solid @divider-color; &-vertical { // 這里的完整類名其實(shí)就是 ant-divider-vertical, 也就是 divider 組件的 type 屬性值為 vertical 時(shí)對應(yīng)的樣式 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';
這樣一來,我相信同學(xué)們也大概了解如何去封裝一個(gè)組件以及關(guān)鍵點(diǎn)了,在源碼中還有很多地方值得我們學(xué)習(xí),比如這里的 ConfigConsumer 的定義與使用,感興趣的同學(xué)歡迎一起交流。
到此這篇關(guān)于基于React封裝組件的實(shí)現(xiàn)步驟的文章就介紹到這了,更多相關(guān)React 封裝組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React路由渲染方式與withRouter高階組件及自定義導(dǎo)航組件應(yīng)用詳細(xì)介紹
這篇文章主要介紹了React路由三種渲染方式、withRouter高階組件、自定義導(dǎo)航組件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-09-09如何創(chuàng)建自己的第一個(gè)React 頁面
React是用于構(gòu)建用戶界面的JavaScript庫,本文主要介紹了如何創(chuàng)建自己的第一個(gè)React頁面,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11解決React報(bào)錯(cuò)JSX?element?type?does?not?have?any?construct
這篇文章主要為大家介紹了解決React報(bào)錯(cuò)JSX?element?type?does?not?have?any?construct?or?call?signatures,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12react中value與defaultValue的區(qū)別及說明
這篇文章主要介紹了react中value與defaultValue的區(qū)別及說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05在react-router4中進(jìn)行代碼拆分的方法(基于webpack)
這篇文章主要介紹了在react-router4中進(jìn)行代碼拆分的方法(基于webpack),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03React語法中設(shè)置TS校驗(yàn)規(guī)則的步驟詳解
這篇文章主要給大家介紹了React語法中如何設(shè)置TS校驗(yàn)規(guī)則,文中有詳細(xì)的代碼示例供大家參考,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-10-10