天天看點

react對antd中Select元件二次封裝

見賢思齊焉,見不賢内自省

建立.js元件,在父元件中引入,傳入自定義屬性

import React from 'react';
import { Select } from 'antd';
import 'antd/dist/antd.css';
import '../styles/select.less';

const {Option} = Select;

class MSelect extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {}
    }
    //父級傳入字段預設值
    static defaultProps = {
        title:"",
        options:[],
    }
    render() {
    //keyField  唯一key
    //valueField 指定目前選中的條目
    //titleField 目前項對應的label
    //options  options數組
        let { title,keyField,valueField,titleField,options, ...rest } = this.props;
        return (
            <div className="select">
                {title&&<p className="select-title">{title}</p>}
                {options.length>0&&<Select {...rest}>
                    {options.map((item)=>{
                        return <Option key={keyField?item[keyField]:(item?.title||item)} value={valueField?item[valueField]:(item?.title||item)}>{titleField?item[titleField]:(item?.title||item)}</Option>
                    })}
                </Select>}
            </div>
        )
    }
}

export default MSelect;
           

less:

.search .select .ant-select-single:not(.ant-select-customize-input) .ant-select-selector {
    width: 200px;
}

.select{
    display: flex;
    flex-direction: row;
    align-items: center;
    padding-bottom: 10px;
    .ant-select-single:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-search-input{
        height: 28px;
        line-height: 28px;
    }
    .ant-select-single:not(.ant-select-customize-input) .ant-select-selector{
        width: 200px;
        height: 28px;
    }
    //options配置中的多選 可輸入 select option 的css
    .ant-select-show-search .ant-select-selector{
        width: 200px;
        min-height: 28px;
        // height: 28px;
        border-radius: 6px;
    }
    .ant-select-show-search .ant-select-selector .ant-select-selection-item{
        height: 20px;
        line-height: 20px;
        border-radius: 6px;
    }
    &-title{
        padding: 0;
        margin: 0;
        min-width: 105px;
        text-align: right;
    }
    &-title-input{
        padding: 0;
        margin: 0;
        min-width: 90px;
        text-align: right;
    }
}
           

使用:

在元件中引入,讓後使用

 <MSelect
      title={`${item.title}:`}
      showArrow={true}
      value={this.state[`${item.keyName}`]}
      onChange={(e) => { this.inputName(`${item.keyName}`, e) }}
      options={item.keyAndValueList}
      keyField="key"
      valueField="key"
      titleField="value"
      dropdownMatchSelectWidth={true} //官方自帶屬性 
></MSelect>
           

資料格式:

keyAndValueList :[
	{ value: "xx管理", key: 0 }, 
	{ value: "xxx管理", key: 1 }, 
	{ value: "xxx管理", key: 2 }
]
           

屬性都是通過 …rest 解構指派的形式來給到MSelect元件的

react對antd中Select元件二次封裝

繼續閱讀