利用ant-design下拉选择框select的labelInValue属性给下拉选项添加图标

这是之前做个小需求遇到的小问题,要做的样式类似下图,当时看了ant-design的文档,并没有直接的例子可以用,但是发现ant-design提供了labelInValue属性,也就可以自定义显示的内容了。
就下拉选项前面要显示一个小图标
实现的代码如下

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

import './index.less';
import 'antd/dist/antd.css';

export default class Demo extends Component {
  state = {
    user: { id: 1, name: '管理员', color: '#126EE3' },
    optionsList: [
      { id: 1, name: '管理员', color: '#126EE3' },
      { id: 2, name: '普通用户', color: '#52C41A' },
      { id: 3, name: '超级管理员', color: '#E8D12C' }
    ]
  };

  getLbael = item => {
    return {
      value: item?.name,
      label: (
        <div>
          <span style={{ display: 'inline-block', width: 10, height: 10, background: item?.color }}></span>
          <span style={{ marginLeft: 8 }}>{item?.name}</span>
        </div>
      )
    };
  };

  selectChange = e => {
    const { optionsList } = this.state;
    const user = optionsList.filter(u => u.name === e.key)?.[0];
    this.setState({
      user
    });
  };

  render() {
    const { user, optionsList } = this.state;
    return (
      <div style={{ margin: 100 }}>
        <Select
          labelInValue
          placeholder="请选择用户类型"
          value={this.getLbael(user)}
          onChange={e => this.selectChange(e)}
          style={{ width: 270 }}
       // getPopupContainer={e => e.parentElement}
        >
          {optionsList.map(item => (
            <Select.Option key={item?.id} value={item?.name}>
              <div>
                <span style={{ display: 'inline-block', width: 10, height: 10, background: item?.color }}></span>
                <span style={{ marginLeft: 8 }}>{item?.name}</span>
              </div>
            </Select.Option>
          ))}
        </Select>
      </div>
    );
  }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值