首页 > 解决方案 > 如何以编程方式在输入单击时留下 Ant Design 选择?

问题描述

我试图弄清楚如何在输入点击时移除焦点/取消选择/离开 Ant Design Select?我有以下组件:

<Select
    className="role-input"
    mode="multiple"
    value={this.selectedValues[config.key]}
    onChange={(value, options) => this.onRoleChange(value, options, index)}
    placeholder={intl.formatMessage({ id: config.placeholder })}
    size="large"
    key={index}
    optionFilterProp="children"
    filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
    onInputKeyDown={() => console.log('hi')}
>
{roleOptions}
</Select>

现在我console.log("hi")有一个inputKeyDown。我想知道如何在 inputKeyDown 上删除焦点/取消选择/保留选择。我看到有一些选择方法,例如blur()其描述是删除焦点,但是,没有任何示例,我无法弄清楚如何实现它。

标签: javascriptreactjsantd

解决方案


您需要分配一个refto Select。然后在current.

const selectRef = React.useRef(null);

const handleInputKeyDown = () => {
  if (selectRef.current) {
    selectRef.current.blur();
  }
};

return (
  <Select
    ref={selectRef}
    onInputKeyDown={handleInputKeyDown}
    ...


推荐阅读