[英]don't clear input on select using React-Select
這個問題沒有很好的答案,所以我來回答一下:
問題是如果你想使用 React-Select 並且你想要持久的輸入值,它不會在選擇或模糊時被清除。 這在組件中當前不受支持,因此需要一種變通方法。
我還就該主題提出的幾個問題之一回答了這個問題https://github.com/JedWatson/react-select/issues/588
https://github.com/JedWatson/react-select/issues/3210
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 在焦點丟失、菜單關閉和值選擇時清除輸入值的默認行為。
例子:
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); // <---
}}
/>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.