【问题标题】:Clear Select component after an option is selected in Ant Design and React在 Ant Design 和 React 中选择一个选项后清除 Select 组件
【发布时间】:2018-12-05 15:07:50
【问题描述】:

我只使用了 Ant Design 的 Select 组件。我需要选择一个选项并将其添加到列表中,但选择该选项后,我想清理选择输入。

// Receiving these props
const {
  fields,
  onAdd,
  selected,
} = this.props;

在下面的代码中,当用户选择一个选项时,它会调用 onAdd 方法将选中的选项添加到其父级列表中。

<Select
  showSearch
  placeholder="Select a field"
  onSelect={(value) => {
    const optionSelected = fields.filter(field => field.id === value)[0];
    onAdd(optionSelected);
  }
  optionFilterProp="children"
  filterOption={(input, option) => (
    option.props.children.toLowerCase()
      .indexOf(input.toLowerCase()) >= 0
  )}
>
  {
    fields.map(field => (
      <Option
        key={field.id}
        value={field.id}
        disabled={selected.some(item => item.id === field.id)}
      >
        {field.name}
      </Option>
    ))
  }
</Select>

谢谢!

【问题讨论】:

    标签: javascript reactjs antd


    【解决方案1】:

    我解决了我的“问题”,只是将 null 设置为 value 属性。

    <Select
      value={null}
      showSearch
      placeholder="Select a field"
      onSelect={(value) => {
        const optionSelected = fields.filter(field => field.id === value)[0];
        onAdd(optionSelected);
      }
      optionFilterProp="children"
      filterOption={(input, option) => (
      option.props.children.toLowerCase()
        .indexOf(input.toLowerCase()) >= 0
      )}
    >
      {
        fields.map(field => (
          <Option
            key={field.id}
            value={field.id}
            disabled={selected.some(item => item.id === field.id)}
          >
            {field.name}
          </Option>
        ))
      }
    </Select>
    

    我几乎将选择用作按钮,以选择并直接在列表中添加项目。我不知道这是否是反模式。

    如果有人有不同的方法,请告诉我。

    谢谢!

    【讨论】:

    • 是的。但这在 标记内不起作用。
    【解决方案2】:

    您需要在您的 JSX 模板中使用 ref="someRef" 并在您的 onSelect 逻辑中使用它。

    其他示例here

    【讨论】:

    • 您好!这比我想象的要简单。我只是将属性值设置为 null。
    猜你喜欢
    • 2020-06-22
    • 2019-10-11
    • 1970-01-01
    • 2020-02-06
    • 2019-03-16
    • 1970-01-01
    • 2019-06-20
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多