【问题标题】:Material-UI: How to show Autocomplete dropdown list only when typing something?Material-UI:如何仅在输入内容时显示自动完成下拉列表?
【发布时间】:2021-07-11 10:07:07
【问题描述】:

如何仅在输入内容时显示 Material-UI Autocomplete 下拉列表?我在我的一个项目中添加了一个 Material-UI Autocomplete 组件。但问题是当我点击TextField 时,它会自动下拉所有列表选项。当用户要输入内容时,我只想下拉建议。下面是我的代码。

import React, { useEffect, useState } from "react";
import { Grid, Popper } from "@material-ui/core";
import axios from "axios";
import Autocomplete from "@material-ui/lab/Autocomplete";

import { useStyles, CssTextField } from "./classes";

export default function SearchItems({ setFieldValue, dialogOpen }) {
  const classes = useStyles();
  const [results, setResults] = useState([]);


  useEffect(() => {
    loadSearchItemsList();
  }, []);
  //load restaurants and tags
  const loadSearchItemsList = async () => {
    try {
      let { data } = await axios.get("/search");
      // console.log(data)
      setResults(data);
    } catch (error) {
      //   setAlert({
      //     showAlert: true,
      //     severity: "error",
      //     message: "Loading failed!",
      //   });
      dialogOpen(true)
    }
  };

    
  return (
    <Grid item xs={12} sm={12} md={12} lg={12} className={classes.gapSpace}>
        <Autocomplete             
          id="free-solo-demo"
          freeSolo             
          getOptionLabel={(option) => option.name}          
          autoComplete            
                
          onChange={(event, newValue) => {
            if (newValue) {
              const { id, type, name } = newValue;
              
              setFieldValue("id", id);
              setFieldValue("type", type);
              setFieldValue("name", name);

            } else {
              setFieldValue("id", null);
              setFieldValue("type", null);
              setFieldValue("name", null);

            }
          }}
          options={results}            
         
          renderInput={(params) => (
            <CssTextField              
              {...params}

              className={classes.input}           
              placeholder="Restaurant, Food"
              variant="outlined"
              id="custom-css-outlined-input"   
                    
            />
            
          )}
        />     
    </Grid>
  );
}

【问题讨论】:

    标签: reactjs autocomplete material-ui


    【解决方案1】:

    您可以控制AutocompleteopeninputValue状态,当inputValue中没有任何内容时调用setOpen(false)关闭菜单列表:

    const [open, setOpen] = useState(false);
    const [inputValue, setInputValue] = useState("");
    
    return (
      <Autocomplete
        open={open}
        onOpen={() => {
          // only open when in focus and inputValue is not empty
          if (inputValue) {
            setOpen(true);
          }
        }}
        onClose={() => setOpen(false)}
        inputValue={inputValue}
        onInputChange={(e, value, reason) => {
          setInputValue(value);
    
          // only open when inputValue is not empty after the user typed something
          if (!value) {
            setOpen(false);
          }
        }}
        options={top100Films}
        renderInput={(params) => (
          <TextField {...params} label="Combo box" variant="outlined" />
        )}
      />
    );
    

    现场演示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-27
      • 1970-01-01
      • 2012-06-09
      • 2021-10-09
      • 1970-01-01
      • 2020-07-05
      • 2021-11-24
      • 2015-10-15
      相关资源
      最近更新 更多