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

Ali*_*ita 7 javascript reactjs react-select

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

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

我还就该主题提出的几个问题之一回答了这个问题 https://github.com/JedWatson/react-select/issues/588
https://github.com/JedWatson/react-select/issues/3210

Ali*_*ita 10

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

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
    />
  )
}
Run Code Online (Sandbox Code Playgroud)

编辑锋利的派克-rnjbr


Ale*_*mia 8

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

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

例子:

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); // <---
      }}
    />
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑relaxed-beaver-e15x0