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

时间:2020-04-16 19:04:26

标签: reactjs autocomplete material-ui

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

1 个答案:

答案 0 :(得分:3)

是的,您可以显式控制open道具,如果您想基于输入了某些内容的用户,那么我建议您也显式控制inputValue道具。

以下是实现此目的的一种可行示例。除了通常指定的道具外,它还指定了onOpen,onClose,onInputChange,open和inputValue道具。

  • onOpen会在认为open应该设置为true时得到called by Material-UI。在以下示例中,handleOpeninputValue为空时会忽略此事件。
  • 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
];

Edit Autocomplete open if input