试试下面的代码。这段代码需要大量重构,但它仍然可以按需要工作。所以,我只是按照文档在 Downshift 上添加了 inputValue 道具。
----- index.js -------
function App() {
const [title, setTitle] = useState("Select an Item");
const [selectedItem, setSelectedItem] = useState(null);
const [inputValue, setInputValue] = useState(""); //added these two to control input of inputbox
const onItemSelected = selectedItem => {
setTitle(selectedItem.name);
setSelectedItem(null);
setInputValue("") // after selection clear input
};
return (
<div className="App">
<h1>{title}</h1>
<Autocomplete
selectedItem={selectedItem}
inputValue={inputValue} // passed down inputValue and setInputValue
setInputValue={setInputValue}
onItemSelected={onItemSelected}
/>
</div>
);
}
----Autocomplete.js--------
function Autocomplete({ selectedItem, onItemSelected, inputValue, setInputValue }) { // get those props
const [items, setItems] = useState([]);
const onInputValueChanged = e => {
setInputValue(e.currentTarget.value) //change a input on inputchange
const items = data.filter(f => f.name.includes(e.currentTarget.value));
setItems(items);
};
return (
<Downshift
inputValue={inputValue} //added
selectedItem={selectedItem}
onChange={onItemSelected}
itemToString={i => (i ? i.name : "")}
>
{({ getInputProps, getItemProps, getMenuProps, isOpen }) => (
<div>
<input {...getInputProps({ onChange: onInputValueChanged })} />
<ul {...getMenuProps()}>
{isOpen &&
items.map(item => (
<li {...getItemProps({ item, key: item.value })}>
{item.name}
</li>
))}
</ul>
</div>
)}
</Downshift>
);
}