MUI 自动完成:如何防止在焦点上打开,而不是在输入更改时打开?

D10*_*001 5 autocomplete reactjs material-ui

我试图阻止自动完成在用户点击后立即打开建议。我希望它只在用户开始输入时打开。似乎没有道具可以实现这一目标。有没有办法使用 onInputChange 来切换自动完成“打开”道具(布尔)。谢谢

Rya*_*ell 10

是的,您可以显式控制open道具,如果您想根据用户输入的内容进行控制,那么我建议您也显式控制inputValue道具。

下面是执行此操作的一种方法的工作示例。除了通常指定的道具之外,这还指定了 onOpen、onClose、onInputChange、open 和 inputValue 道具。

  • onOpen将得到的材料的UI叫在其认为open应设置为truehandleOpen在下面的示例中,当inputValue为空时忽略此事件。
  • onClose将得到的材料的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
];
Run Code Online (Sandbox Code Playgroud)

如果输入,则编辑自动完成打开