最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - don't clear input on select using React-Select - Stack Overflow

programmeradmin5浏览0评论

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. 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

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. 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/3210

Share Improve this question edited Oct 15, 2020 at 22:23 Alita asked Oct 10, 2020 at 21:38 AlitaAlita 8792 gold badges9 silver badges20 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

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.

In other words, we need to disable ReactSelect's default behavior of clearing the input value on focus loss, menu close, and value select.

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

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

发布评论

评论列表(0)

  1. 暂无评论