多选Tag效果图
封装组件代码
使用class类组件进行基本tag标签封装
基本tag组件代码
import React, { Component } from 'react';
import _ from 'lodash';
import './index.scss';
import { CheckCircleOutlined } from '@ant-design/icons';
class TagFormItem extends Component {
constructor(props) {
console.log(props, 'props---');
super(props);
this.state = {
tagValue: props.value,
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (!_.isEqual(nextProps.value, this.props.value)) {
this.setState({
tagValue: nextProps.value,
});
}
}
changeValue = (v) => {
console.log(v, 'vvvvvvvvv');
const { tagValue } = this.state;
const newTagValue = tagValue?.includes(v)
? tagValue.filter((el) => el !== v)
: [...tagValue, v];
this.setState(
{
tagValue: newTagValue,
},
() => {
this.props.onChange(v, newTagValue);
},
);
};
render() {
const { dataSource } = this.props;
const { tagValue } = this.state;
return (
<div className="tagFormItem">
{dataSource?.map((el) => (
<div
className={tagValue?.includes(el.value) ? 'tagForm active' : 'tagForm'}
onClick={() => this.changeValue(el.value)}
key={el.value}
>
{el.label}
{tagValue?.includes(el.value) ? <CheckCircleOutlined /> : ''}
</div>
))}
</div>
);
}
}
export default TagFormItem;
css代码
.tagFormItem {
display: flex;
flex-direction: row;
flex-flow: row wrap;
white-space: wrap;
.tagForm {
margin-top: 8px;
text-align: center;
margin-left: 15px;
width: 95px;
height: 28px;
line-height: 28px;
border: 1px solid #f9b37a;
border-radius: 5px;
color: #313233;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.active {
background-color: #f8f8f8;
color: #ff6a00;
}
}
引入封装好的组件
在函数式组件中引入
import React, { useState } from 'react';
import TagFormItem from '../../../components/TagSelected';
const Published = () => {
const [selectedTreeIdList, setSelectedTreeIdList] = useState([]);
const data = [
{ label: '秦始皇', value: 11 },
{ label: '汉高祖', value: 12 },
{ label: '汉武帝', value: 13 },
{ label: '唐太宗', value: 14 },
{ label: '唐高宗', value: 15 },
{ label: '武则天', value: 16 },
{ label: '唐玄宗', value: 17 },
];
// 选中标签
const TagFormChange = (val, newVal) => {
console.log(val, newVal, '00000');
setSelectedTreeIdList([...newVal]);
};
return (
<div>
<TagFormItem
value={selectedTreeIdList}
onChange={TagFormChange}
dataSource={data?.map((ds) => ({ ...ds, label: ds.label, value: ds.value }))}
/>
</div>
);
};
export default Published;