日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Antd的Select組件二次封裝

作者:讀心悅 更新時間: 2023-08-01 編程語言

提示:Select組件二次封裝的目的,是為了在系統里面更方便、簡潔地使用Select

這是官方寫的使用方法是:

import React from 'react';
import { Select } from 'antd';

const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};

const App: React.FC = () => (
  <>
    <Select
      defaultValue="lucy"
      style={{ width: 120 }}
      onChange={handleChange}
      options={[
        { value: 'jack', label: 'Jack' },
        { value: 'lucy', label: 'Lucy' },
        { value: 'Yiminghe', label: 'yiminghe' },
        { value: 'disabled', label: 'Disabled', disabled: true },
      ]}
    />
  </>
);

export default App;

如果是在一個復雜的應用中,會有很多地方都會使用到Select組件的,而且每一個場景不同,需要設置不同的參數。

這樣似乎很繁瑣。現在需要對Select進行二次封裝,符合自己的應用場景。

封裝后的組件,只需要傳入一個屬性:config。

二次封裝的組件命名為:DXSelect。

DXSelect組件默認設置一個寬度,放在style屬性里面。例如: styles = { width: "200px" }

config屬性包含了一下屬性:

options:定義select的選項,作為必填參數;

styles:樣式,便于修改樣式。

otherProps:其他屬性,作為組件的擴展屬性吧,在不同場景中,需要設置不同的參數,除了styles和options,其他屬性都放在otherProps里面。

現在先定義一下屬性的數據類型,這樣嚴謹一點:

interface optionItem {
    itemKey?: string,
    itemValue?: string
}
interface ConfigProps {
    options: optionItem[],// 下拉框選項
    styles?: object, // 寬度
    otherProps?: object, // 其他屬性
}
interface Props {
    config: ConfigProps
}

組件代碼為:

const DXSelect: React.FC<Props> = ({ config }) => {
    const { styles = { width: "200px" }, options, otherProps } = config
    return <Select style={styles} {...otherProps}>
        {
            options.map((item: any) => <Select.Option value={item.itemKey}>{item.itemValue}</Select.Option>)
        }
    </Select>
}

這樣引入該組件:<DXSelect config={defaultConfig} />

defaultConfig定義為:

  const defaultConfig = {
    options: [
      { itemKey: "123", itemValue: "test" },
      { itemKey: "124", itemValue: "test4" }
    ],
  }

效果如圖:
在這里插入圖片描述
現在修改一下樣式,就在styles屬性添加新的樣式,比如:

  const defaultConfig = {
    options: [
      { itemKey: "123", itemValue: "test" },
      { itemKey: "124", itemValue: "test4" }
    ],
    styles:{
      width:"100px"
    }
  }

修改的效果如下圖:
在這里插入圖片描述
其他的參數設置如下:

  const defaultConfig = {
    options: [
      { itemKey: "123", itemValue: "test" },
      { itemKey: "124", itemValue: "test4" }
    ],
    styles: {
      width: "100px"
    },
    otherProps: {
      allowClear: true,
      onChange: (value: string, option: any,) => {
        console.log("value", value, option)
      }
    }
  }

這就Select的二次封裝。

組件已經發布到npm上,有興趣的同學,可以體驗一下:npm i duxin-design

原文鏈接:https://blog.csdn.net/xuelian3015/article/details/131713856

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新