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('');
    }
  };
相关推荐
子兮曰1 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰1 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万1 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝1 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋1 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁1 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄1 天前
JavaScript 隐式全局变量解析
javascript
汉堡大王95271 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大1 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师1 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端