我正尝试阻止用户点击后自动完成打开建议的操作。我希望仅在用户开始输入时打开它。似乎没有实现这一目标的工具。是否可以使用onInputChange来切换“自动完成”“打开”道具(布尔)。谢谢
是的,您可以显式控制open
道具,如果您要基于已键入内容的用户,那么我建议您也显式控制inputValue
道具。
下面是一个实现此目的的方法示例。除了通常指定的道具外,它还指定了onOpen,onClose,onInputChange,open和inputValue道具。
onOpen
当Material-UI认为open
应将其设置为时,它将被调用true
。handleOpen
在下面的示例中,当inputValue
为空时,将忽略此事件。onClose
当Material-UI认为open
应将其设置为时,它将被调用false
。下面的示例无条件调用,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
];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句