项目场景:使用的antd的Select组件的多选模式限制多选数量
问题描述
提示:限制多选的数量:
例如:在使用antd的Select组件的时候,官方并没有提供多选的数量限制,而且这种的情况也比较常见,姑且在antd的Select上面进行了二次封装,具体代码如下:
import { useState } from 'react';
import { Select as AntdSelect } from 'antd';
export default function Select(props) {
const { maxLength, value, onChange, mode, ...otherProps } = props;
const [initValue, setInitValue] = useState<string[] | string | undefined>(value);
return (
<AntdSelect
onChange={(selectValue) => {
// 模式为多选且存在最大值时,当最大长度大于输入长度时触发校验
if (mode === 'multiple' && maxLength && selectValue?.length > maxLength) {
selectValue?.pop(); // 删除多余项
setInitValue(selectValue);
}
onChange(selectValue);
}}
value={initValue}
mode={mode}
{...otherProps}
/>
)
}
// 使用示例,这里建议使用options属性渲染
<Select options={yourOptions} maxLength={3} mode='multiple'/>