【问题标题】:MUI Autocomplete: How to prevent open on focus, instead open on input change?MUI 自动完成:如何防止在焦点上打开,而不是在输入更改时打开?
【发布时间】:2020-07-30 03:44:22
【问题描述】:

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

【问题讨论】:

    标签: reactjs autocomplete material-ui


    【解决方案1】:

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

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

    • 只要open 认为应该将open 设置为trueonOpen 就会得到called by Material-UI。下例中的handleOpen,当inputValue 为空时忽略此事件。
    • 只要open 认为应该将open 设置为falseonClose 就会得到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
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 2012-09-11
      • 2020-03-21
      相关资源
      最近更新 更多