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('');
    }
  };
相关推荐
恋猫de小郭5 分钟前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅7 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60617 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅8 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅8 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅8 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅9 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊9 小时前
jwt介绍
前端