0
点赞
收藏
分享

微信扫一扫

antd的Select组件的多选模式限制多选数量

笑望叔叔 2022-04-14 阅读 110

项目场景:使用的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}
      {...otherProps}
    />
  )
}

举报

相关推荐

0 条评论