不要使用 React-Select 清除 select 上的输入

don't clear input on select using React-Select

这个问题没有很好的答案所以我来回答:

问题是如果你想使用 React-Select 并且你想要在 select 上不被清除或模糊的持久输入值。该组件当前不支持此功能,因此需要解决方法。

我也回答了关于这个话题提出的几个问题之一 https://github.com/JedWatson/react-select/issues/588
https://github.com/JedWatson/react-select/issues/3210

您还可以使用 this 来增强它以获得所需的效果

const App = () => {
  const [input, setInput] = useState("");
  const [inputSave, setSave] = useState("");
  
  return (
    <Select
      placeholder={inputSave} // when blurred & value == "" this shows
      value="" // always show placeholder
      inputValue={input} // allows you continue where you left off
      onInputChange={setInput} // allows for actually typing
      onMenuClose={() => setSave(input)} // before the input is cleared, save it
      onFocus={() => {
        setInput(inputSave);
        setSave(""); // prevents undesired placeholder value
      }} 
      blurInputOnSelect  // actually allows for ^^ to work
    />
  )
}

解决此问题的最佳方法是手动设置输入值(处理 onInputChange() 事件)仅当用户实际输入时

换句话说,我们需要禁用 ReactSelect 在焦点丢失、菜单关闭和值 select 时清除输入值的默认行为。

示例:

export default function App() {
  const [input, setInput] = useState("");

  const options = [
    { label: "first option", value: 1 },
    { label: "second option", value: 2 },
    { label: "third option", value: 3 }
  ];

  return (
    <Select
      options={options}
      inputValue={input}
      onInputChange={(value, action) => {
        // only set the input when the action that caused the
        // change equals to "input-change" and ignore the other
        // ones like: "set-value", "input-blur", and "menu-close"
        if (action.action === "input-change") setInput(value); // <---
      }}
    />
  );
}