ant design pro使用select添加特殊项实现禁用及清空回填项功能

在这里插入图片描述
需求:
1.选择 全院 时,其他项禁用
2.已选择其他项目后再选择全院,回填内容只保留 全院
坑:
因为整体是个查询条目,用form包裹了,所以组件的onChange等内容不能使用.
上代码:
渲染代码

<Form form={form} style={{ display: 'flex' }} onValuesChange={formChange}>
      <Form.Item
        name="locID"
        label="科室"
        style={{ margin: '2px 10px', textAlign: 'left' }}
        className="ie-right"
      >
        <Select
          showSearch
          allowClear
          placeholder="[科室]"
          mode="multiple"
          style={{ width: 180 }}
          onSelect={selectAll}
          onDeselect={deselectAll}
        >
          {optionsCreate(locList)}
        </Select>
      </Form.Item>

逻辑代码

  //当选中  全院  时,其它选项禁用
  const [flag, setFlag] = useState<boolean>(false);

  //科室下拉框
  const optionsCreate = (arr: any) => {
    const options: any = [];
    if (!arr) {
      return;
    }
    for (let i = 0; i < arr.length; i++) {
      options.push(
        <Option
          key={arr[i].LocID}
          value={arr[i].LocID}
          disabled={arr[i].LocID == 'ALL' ? false : flag}
        >
          {arr[i].LocDesc}
        </Option>,
      );
    }
    return options;
  };

  //选中  全院  时,其它选项禁用
  const selectAll = (value: any, option: any) => {
    if (option.key === 'ALL') {
      setFlag(true);
    } else {
      setFlag(false);
    }
  };
  //取消选中  全院  时,其它选项可用
  const deselectAll = (value: any, option: any) => {
    if (option.key === 'ALL') {
      setFlag(false);
    }
  };

  const formChange = () => {
    const { locID } = form.getFieldsValue();
    if (locID.length > 1 && locID.includes('ALL')) {
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      !flag ? form.setFieldsValue({ locID: 'ALL' }) : form.setFieldsValue({ locID });
    }
  };


版权声明:本文为weixin_46424838原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。