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('');
    }
  };
相关推荐
程序猿--豪29 分钟前
webpack详细打包配置,包含性能优化、资源处理...
前端·webpack·性能优化
小小小小宇1 小时前
前端监控 SDK
前端
csj501 小时前
前端基础之《Vue(11)—自定义指令》
前端·vue
fxshy1 小时前
ai聊天流式响应,阻塞式和流式响应 nginx遇到的坑
运维·javascript·nginx
街尾杂货店&1 小时前
HTML word属性
前端·html
这颗橘子不太甜QAQ1 小时前
Husky使用技巧
javascript·git·代码规范
M1A11 小时前
全栈开发必备:Windows安装VS Code全流程
前端·后端·全栈
蜗牛快跑1231 小时前
github 源码阅读神器 deepwiki,自动生成源码架构图和知识库
前端·后端
嘻嘻嘻嘻嘻嘻ys1 小时前
《Vue 3.4响应式超级工厂:Script Setup工程化实战与性能跃迁》
前端·后端
장숙혜1 小时前
ElementUi的tabs样式太难修改,自定义tabs标签页
前端·javascript