选择antd后如何关闭下拉菜单

how to close the dropdown after selection antd

目标: select 选择选项后关闭下拉菜单。这适用于正常的 select 下拉菜单,但不适用于标签。

代码:

 <Select
    mode="multiple"
    style={{ width: "100%" }}
    placeholder="select one country"
    defaultValue={["china"]}
    onChange={handleChange}
    optionLabelProp="label"
  >
    <Option value="china" label="China">
      <div className="demo-option-label-item">
        <span role="img" aria-label="China">
          
        </span>
        China (中国)
      </div>
    </Option>
    <Option value="usa" label="USA">
      <div className="demo-option-label-item">
        <span role="img" aria-label="USA">
          
        </span>
        USA (美国)
      </div>
    </Option>
    <Option value="japan" label="Japan">
      <div className="demo-option-label-item">
        <span role="img" aria-label="Japan">
          
        </span>
        Japan (日本)
      </div>
    </Option>
    <Option value="korea" label="Korea">
      <div className="demo-option-label-item">
        <span role="img" aria-label="Korea">
          
        </span>
        Korea (韩国)
      </div>
    </Option>
  </Select>

Codesandbox:https://codesandbox.io/s/custom-selection-render-antd-4-19-5-forked-9mm82d

您可以在 Select 上使用 useRef 并在用户触发其上的值更改时调用 blur

The sandbox

import React, { useRef, useCallback } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "antd";

const { Option } = Select;

const App = () => {
  //introduce `selectRef` for `Select`
  const selectRef = useRef()

  const handleChange = useCallback((value) => {
    selectRef.current.blur() //whenever a user triggers value change, we call `blur()` on `Select`
  }, [])

  return <Select
  mode="multiple"
  style={{ width: "100%" }}
  placeholder="select one country"
  defaultValue={["china"]}
  onChange={handleChange}
  optionLabelProp="label"
  ref={selectRef} //add ref here
>
  <Option value="china" label="China">
    <div className="demo-option-label-item">
      <span role="img" aria-label="China">
        
      </span>
      China (中国)
    </div>
  </Option>
  <Option value="usa" label="USA">
    <div className="demo-option-label-item">
      <span role="img" aria-label="USA">
        
      </span>
      USA (美国)
    </div>
  </Option>
  <Option value="japan" label="Japan">
    <div className="demo-option-label-item">
      <span role="img" aria-label="Japan">
        
      </span>
      Japan (日本)
    </div>
  </Option>
  <Option value="korea" label="Korea">
    <div className="demo-option-label-item">
      <span role="img" aria-label="Korea">
        
      </span>
      Korea (韩国)
    </div>
  </Option>
</Select>
}

ReactDOM.render(
  <App/>,
  document.getElementById("container")
);