简体   繁体   English

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

[英]don't clear input on select using React-Select

There wasn't a good answer to this question so I'll answer it:这个问题没有很好的答案,所以我来回答一下:

The problem is if you want to use the React-Select and you want persistent input value that doesn't get cleared on select or blur.问题是如果你想使用 React-Select 并且你想要持久的输入值,它不会在选择或模糊时被清除。 This is not currently supported within the component, so a work-around is necessary.这在组件中当前不受支持,因此需要一种变通方法。

I also answered this on one of the several issues raised on this topic https://github.com/JedWatson/react-select/issues/588我还就该主题提出的几个问题之一回答了这个问题https://github.com/JedWatson/react-select/issues/588
https://github.com/JedWatson/react-select/issues/3210 https://github.com/JedWatson/react-select/issues/3210

you can also augment this with this to get desired effects你也可以用来增强以获得所需的效果

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
    />
  )
}

编辑sharp-pike-rnjbr

The best way to go about this would be manually setting the input value (handling the onInputChange() event) only when the user is actually typing .解决此问题的最佳方法是仅在用户实际键入时手动设置输入值(处理onInputChange()事件)。

In other words, we need to disable ReactSelect's default behavior of clearing the input value on focus loss, menu close, and value select.换句话说,我们需要禁用 ReactSelect 在焦点丢失、菜单关闭和值选择时清除输入值的默认行为。

Example:例子:

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); // <---
      }}
    />
  );
}

编辑轻松海狸-e15x0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM