react+antd封装一个可回车自定义option的select并且与某些内容相互禁用

需求背景

一个select框 现在要求可多选 并且原有一个any的选项 其他选项为输入后回车自己增加 若选择了any 则其他选项不可选择反之选择其他选项any不可选择 并且回车新增时也不可直接加入到选中数组只加入到option内 并且不可重复添加新内容

实现过程

javascript 复制代码
 <Form.Item label={formatMessage({ id: 'label.alarm.SourceAddress' })} 
 name="sourceAddress">
          <Select
            mode="multiple"
            maxTagCount={3}
            showSearch
            searchValue={inputValue}
            onChange={(e) => createSelectionHandler(e, 'any', sourceList, setSourceList)}
            placeholder={formatMessage({ id: 'select.placeholder' })}
            onSearch={setInputValue}
            onInputKeyDown={sourceHandleKeyDown}
            options={sourceList}
            getPopupContainer={(triggerNode) => triggerNode.parentElement || 
            document.body}
          />
 </Form.Item>
 //js部分
  // 源地址列表
  const [sourceList, setSourceList] = useState([{ value: 'any', label: 'any', disabled: 
  false }]);
  // 源地址输入框
  const [inputValue, setInputValue] = useState('');
  // 通用处理函数
  const createSelectionHandler = (specialValue, key, stateList, setState) => {
    const newList = stateList.map((item) => ({
      ...item,
      disabled: specialValue.includes(key)
        ? item.value !== key // 如果选中特殊值,禁用其他选项
        : specialValue.length > 0 // 如果选中普通值,禁用特殊值
        ? item.value === key
        : false, // 没有选中时恢复默认
    }));
    setState(newList);
  };
  // 源地址处理键盘事件(回车)
  const sourceHandleKeyDown = (e) => {
    if (e.key === 'Enter' && inputValue.trim()) {
      const newValue = inputValue.trim();
      const lis = addAlarmForm.getFieldValue('sourceAddress');
      if (!lis.includes(newValue)) {
        if (lis.includes('any')) {
          setSourceList([
            ...sourceList,
            {
              value: newValue,
              label: newValue,
              disabled: true,
            },
          ]);
        } else {
          setSourceList(
            [
              ...sourceList,
              {
                value: newValue,
                label: newValue,
                disabled: false,
              },
            ].map((item) => ({
              ...item,
              disabled: item.value == 'any',
            })),
          );

          addAlarmForm.setFieldsValue({
            sourceAddress: [...lis, newValue],
          });
        }
      }
      setInputValue('');
    }
  };
相关推荐
IT_陈寒36 分钟前
Redis性能翻倍的5个冷门技巧,90%的开发者从不知道第3点!
前端·人工智能·后端
WebGIS开发43 分钟前
新中地三维GIS开发智慧城市效果和应用场景
前端·人工智能·gis·智慧城市·webgis
課代表1 小时前
Acrobat DC 文本域表单验证中的 js 使用
javascript·正则表达式·表单验证·数据完整性·字段验证·事件对象·自定义验证
鱼樱前端2 小时前
uni-app快速入门章法(一)
前端·uni-app
zhangxuyu11182 小时前
flex布局学习记录
前端·css·学习
掘金一周2 小时前
🍏让前端去做 iPhone 的液态玻璃❓ | 掘金一周 10.2
前端·人工智能·后端
用户6387994773052 小时前
Next.js 多语言对决:next-intl vs next-i18next vs Intlayer
javascript
Keepreal4962 小时前
谈谈对javascript原型链的理解以及原型链的作用
前端·javascript
itslife2 小时前
vite 源码 - 配置
前端·javascript
Keepreal4962 小时前
Typescript中type和interface的区别
前端·typescript