材质 UI 自动完成下拉定位

时间:2021-01-25 09:01:42

标签: javascript css reactjs material-ui

是否有任何简单的方法可以自定义 Material UI 自动完成功能,以便可以相对于文本光标定位 Popper 下拉菜单(类似于 VS Code Intellisense 下拉菜单)?我有一个多行 Textfield 组件作为输入字段。

代码看起来像这样:

import React from "react";
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles';
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import Chip from '@material-ui/core/Chip';
import { Popper } from "@material-ui/core";



const targetingOptions = [
  { label: "(", type: "operator" },
  { label: ")", type: "operator" },
  { label: "OR", type: "operator" },
  { label: "AND", type: "operator" },
  { label: "Test Option 1", type: "option" },
  { label: "Test Option 2", type: "option" },
];


const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      '& .MuiAutocomplete-inputRoot': {
        alignItems: 'start'
      }
    },
  }),
);




export default () => {
  const classes = useStyles();

  const CustomPopper = function (props) {
    return <Popper {...props} style={{ width: 250, position: 'relative' }} />;
  };
  

  return (
    <div>
        <Autocomplete
        className={classes.root}
        multiple
        id="tags-filled"
        options={targetingOptions.map((option) => option.label)}
        freeSolo
        disableClearable
        PopperComponent={CustomPopper}
        renderTags={(value: string[], getTagProps) =>
          value.map((option: string, index: number) => (
            <Chip variant="outlined" label={option} {...getTagProps({ index })} />
          ))
        }
        renderInput={(params) => (
          <TextField {...params} variant="outlined" multiline={true} rows={20} />
        )}
      />
    </div>
  );
};

1 个答案:

答案 0 :(得分:0)

材质 ui 的自动完成有一个 PopperComponent 属性,您可以使用它来创建一个具有您想要的 placement 属性的自定义 popper。

检查这个:https://github.com/mui-org/material-ui/issues/19376