如何仅在输入内容时显示 Material-UI
Autocomplete
下拉列表?我在我的一个项目中添加了一个 Material-UI Autocomplete
组件。但问题是,当我单击TextField
时,它会自动下拉所有列表选项。当用户要输入内容时,我只想下拉建议。下面是我的代码。
import React, { useEffect, useState } from "react";
import { Grid, Popper } from "@material-ui/core";
import axios from "axios";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { useStyles, CssTextField } from "./classes";
export default function SearchItems({ setFieldValue, dialogOpen }) {
const classes = useStyles();
const [results, setResults] = useState([]);
useEffect(() => {
loadSearchItemsList();
}, []);
//load restaurants and tags
const loadSearchItemsList = async () => {
try {
let { data } = await axios.get("/search");
// console.log(data)
setResults(data);
} catch (error) {
// setAlert({
// showAlert: true,
// severity: "error",
// message: "Loading failed!",
// });
dialogOpen(true)
}
};
return (
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.gapSpace}>
<Autocomplete
id="free-solo-demo"
freeSolo
getOptionLabel={(option) => option.name}
autoComplete
onChange={(event, newValue) => {
if (newValue) {
const { id, type, name } = newValue;
setFieldValue("id", id);
setFieldValue("type", type);
setFieldValue("name", name);
} else {
setFieldValue("id", null);
setFieldValue("type", null);
setFieldValue("name", null);
}
}}
options={results}
renderInput={(params) => (
<CssTextField
{...params}
className={classes.input}
placeholder="Restaurant, Food"
variant="outlined"
id="custom-css-outlined-input"
/>
)}
/>
</Grid>
);
}
可以控制
open
的inputValue
和Autocomplete
状态,并在setOpen(false)
没有任何内容时调用inputValue
关闭菜单列表:
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
return (
<Autocomplete
open={open}
onOpen={() => {
// only open when in focus and inputValue is not empty
if (inputValue) {
setOpen(true);
}
}}
onClose={() => setOpen(false)}
inputValue={inputValue}
onInputChange={(e, value, reason) => {
setInputValue(value);
// only open when inputValue is not empty after the user typed something
if (!value) {
setOpen(false);
}
}}
options={top100Films}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>
);
您可以只检查输入值的长度,因为它更干净、更可靠。如果您不想更改自动完成功能并隐藏下拉图标,也可以使用
forcePopupIcon={false}
代替 freeSolo
。
const AutoComplete = () => {
const [inputValue, setInputValue] = useState("");
return (
<Autocomplete
open={inputValue.length !== 0}
inputValue={inputValue}
onInputChange={(_, value) => setInputValue(value)}
options={top100Films}
getOptionLabel={(option) => option.title}
fullWidth
style={{ width: 300 }}
forcePopupIcon={false}
renderInput={(params) => (
<TextField {...params} label="Search Movie" variant="outlined" />
)}
/>
);
};
export default AutoComplete;