这是之前做个小需求遇到的小问题,要做的样式类似下图,当时看了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>
);
}
}