我正试图阻止用户点击后自动完成打开建议。我希望仅在用户开始输入时打开它。似乎没有实现这一目标的工具。 是否可以使用onInputChange来切换“自动完成”“打开”道具(布尔)。 谢谢
答案 0 :(得分:3)
是的,您可以显式控制open
道具,如果您想基于输入了某些内容的用户,那么我建议您也显式控制inputValue
道具。
以下是实现此目的的一种可行示例。除了通常指定的道具外,它还指定了onOpen,onClose,onInputChange,open和inputValue道具。
onOpen
会在认为open
应该设置为true
时得到called by Material-UI。在以下示例中,handleOpen
在inputValue
为空时会忽略此事件。onClose
会在认为open
应该设置为false
时得到called by Material-UI。下面的示例无条件调用setOpen(false)
,因此它在与默认行为相同的所有情况下仍然关闭。handleInputChange
除了管理inputValue
状态之外,还根据值是否为空来切换open
状态。/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
export default function ComboBox() {
const [inputValue, setInputValue] = React.useState("");
const [open, setOpen] = React.useState(false);
const handleOpen = () => {
if (inputValue.length > 0) {
setOpen(true);
}
};
const handleInputChange = (event, newInputValue) => {
setInputValue(newInputValue);
if (newInputValue.length > 0) {
setOpen(true);
} else {
setOpen(false);
}
};
return (
<Autocomplete
id="combo-box-demo"
open={open}
onOpen={handleOpen}
onClose={() => setOpen(false)}
inputValue={inputValue}
onInputChange={handleInputChange}
options={top100Films}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
{ title: "The Shawshank Redemption", year: 1994 },
{ title: "The Godfather", year: 1972 },
{ title: "The Godfather: Part II", year: 1974 }
// and many more options
];