基于React封裝組件的實(shí)現(xiàn)步驟
前言
很多小伙伴在第一次嘗試封裝組件時(shí)會(huì)和我一樣碰到許多問(wèn)題,比如人家的組件會(huì)有 color 屬性,我們?cè)谑褂媒M件時(shí)傳入組件文檔中說(shuō)明的屬性值如 primary ,那么這個(gè)組件的字體顏色會(huì)變?yōu)?primary 對(duì)應(yīng)的顏色,這是如何做到的?還有別人封裝的組件類(lèi)名都有自己獨(dú)特的前綴,這是如何處理的呢,難道是 css 類(lèi)名全部加上前綴嗎,這也太麻煩了!
如果你正在困惑這些問(wèn)題,你可以看看這篇文章。
我會(huì)參照 antd的divider組件 來(lái)講述如何基于React封裝一個(gè)組件,以及解答上述的一些問(wèn)題,請(qǐng)耐心看完!
antd 是如何封裝組件的
倉(cāng)庫(kù)地址
- antd 倉(cāng)庫(kù)地址:https://github.com/ant-design/ant-design
- divider 組件在下圖對(duì)應(yīng)目錄下 (代碼我會(huì)拷貝過(guò)來(lái),感興趣的還是可以去克隆一下倉(cāng)庫(kù))

divider 組件源代碼
antd 的源碼使用了 TypeScript 語(yǔ)法,因此不了解語(yǔ)法的同學(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' /> 這樣來(lái)傳入 type 屬性,那么 divider 分割線樣式就會(huì)渲染為垂直分割線,是不是很熟悉!
export interface DividerProps { // interface 是 TypeScript 的語(yǔ)法
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是比較常見(jiàn)的屬性,這代表我們可以 <Divider type='vertical' className='myClassName' style={{width: '1em'}} /> 這樣使用這些屬性。
如何設(shè)置統(tǒng)一類(lèi)名前綴
我們知道,antd 的組件類(lèi)名會(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 ,這里是通過(guò) 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ì)生成的類(lèi)名前綴為 ant-divider 。
如何處理樣式與類(lèi)名
我們封裝的組件肯定是有預(yù)設(shè)的樣式,又因?yàn)闃邮揭ㄟ^(guò)類(lèi)名來(lái)定義,而我們傳入的屬性值則會(huì)決定組件上要添加哪個(gè)類(lèi)名,這又是如何實(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),它通過(guò) classNames 方法(classNames是React處理多類(lèi)名的組件)定義了一個(gè)所有類(lèi)名的常量,然后傳給了 div 中的 className 屬性。
其實(shí)生成的類(lèi)名也就是 ant-divider-horizontal 這個(gè)樣子,那么css中以此類(lèi)名定義的樣式也就自然會(huì)生效了。而 className 和 style 屬性則是通過(guò) {...restProps} 來(lái)傳入。
最后我們?cè)倏纯此腸ss樣式代碼是怎么寫(xiě)的!
divider 組件樣式源代碼
antd 組件的樣式使用 Less 書(shū)寫(xiě),不了解 Less 語(yǔ)法的同學(xué)一定要了解一下。
@import '../../style/themes/index';
@import '../../style/mixins/index';
@divider-prefix-cls: ~'@{ant-prefix}-divider'; // 可以看到這里對(duì)應(yīng)的也就是之前說(shuō)到的類(lèi)名前綴
.@{divider-prefix-cls} {
.reset-component();
border-top: @border-width-base solid @divider-color;
&-vertical { // 這里的完整類(lèi)名其實(shí)就是 ant-divider-vertical, 也就是 divider 組件的 type 屬性值為 vertical 時(shí)對(duì)應(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';
這樣一來(lái),我相信同學(xué)們也大概了解如何去封裝一個(gè)組件以及關(guān)鍵點(diǎn)了,在源碼中還有很多地方值得我們學(xué)習(xí),比如這里的 ConfigConsumer 的定義與使用,感興趣的同學(xué)歡迎一起交流。
到此這篇關(guān)于基于React封裝組件的實(shí)現(xiàn)步驟的文章就介紹到這了,更多相關(guān)React 封裝組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React項(xiàng)目配置prettier和eslint的方法
這篇文章主要介紹了React項(xiàng)目配置prettier和eslint的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
完美解決react-codemirror2?編輯器需點(diǎn)擊一下或者延時(shí)才顯示數(shù)據(jù)的問(wèn)題
這篇文章主要介紹了react-codemirror2編輯器需點(diǎn)擊一下或者延時(shí)才顯示數(shù)據(jù)的問(wèn)題,解決方法也很簡(jiǎn)單,需要手動(dòng)引入自動(dòng)刷新的插件,配置一下參數(shù)就可以了,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08
React組件化的一些額外知識(shí)點(diǎn)補(bǔ)充
React是一個(gè)用于構(gòu)建用戶界面的JavaScript庫(kù),下面這篇文章主要給大家介紹了關(guān)于React組件化的一些額外知識(shí)點(diǎn),文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10
react?card?slider實(shí)現(xiàn)滑動(dòng)卡片教程示例
這篇文章主要為大家介紹了react?card?slider實(shí)現(xiàn)滑動(dòng)卡片教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09

