我在我的项目中使用material ui autocomplete。
选项列表最初为空,输入更改后,列表将被填充。 因此,在初始空状态期间,我需要在选项区域中显示这样的占位符。
在搜索时,我发现仅在输入区域(附图)中填充了占位符,而不是在选项列表区域中。
关于如何实现这一目标有什么想法吗?
您可以使用自动完成组件的
noOptionsText
属性来实现这一点。你可以像这样使用它noOptionsText="Type to search"
。请注意,即使您输入了某些内容但没有结果,它也会显示“输入要搜索”。要解决这个问题,您可以有条件地在 noOptionsText 中添加值。
在下面的示例中,当没有输入值时,我将值设置为“键入搜索”。否则我会显示“无结果”。
您可以在这里检查沙箱:https://codesandbox.io/p/sandbox/vigorous-meadow-dsdlm5
<Autocomplete
disablePortal
id="combo-box-demo"
options={inputValue ? top100Films : []}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Movie" />}
inputValue={inputValue}
onInputChange={(event) => {
console.log(event?.target?.value);
if (event?.target?.value) {
setInputValue(event.target.value);
} else {
setInputValue("");
}
}}
noOptionsText={inputValue ? "No result" : "Type to search"}
/>