首页 > 解决方案 > React,Material UI,Select,disableScrollLock,使菜单位置相对于锚点

问题描述

import React from "react";
import "./styles.css";

import Input from "@material-ui/core/Input";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const names = [
  "Oliver Hansen",
  "Van Henry",
  "April Tucker",
  "Ralph Hubbard",
  "Omar Alexander",
  "Carlos Abbott",
  "Miriam Wagner",
  "Bradley Wilkerson",
  "Virginia Andrews",
  "Kelly Snyder"
];

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250
    }
  },
  disableScrollLock: true
};

export default function App() {
  const [personName, setPersonName] = React.useState([]);

  const handleChange = event => {
    setPersonName(event.target.value);
  };

  return (
    <div className="App" style={{ height: "1000px" }}>
      <FormControl>
        <Select
          labelId="demo-mutiple-name-label"
          id="demo-mutiple-name"
          multiple
          value={personName}
          onChange={handleChange}
          input={<Input />}
          MenuProps={MenuProps}
        >
          {names.map(name => (
            <MenuItem key={name} value={name}>
              {name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

代码也可以在这里找到https://codesandbox.io/s/awesome-leaf-ooko1

我正在使用 React 16,最新的 Material UI 核心,Material UI Select Component

我在这里要做的是当我打开下拉菜单(disableScrollLock = true)时,当我滚动窗口时,下拉菜单将相对于未固定在窗口上的锚元素。我怎样才能做到这一点?

标签: javascriptreactjsmaterial-ui

解决方案


我不熟悉 React,但我设法找到了一个具有不同组件的工作示例。

看到这个答案:https ://stackoverflow.com/a/54011607/152016

Coder 使用 aReportComboBox而不是 a Select,但他解决了您的代码段的另一个问题:增加选择大小。

当您在代码段中选择很多项目时,会出现 UI 问题。

足够离题了,我已经更改了答案的片段以启用滚动(body { height: 3000px; }例如通过设置,您可以看到滚动将选择框保持在其位置:https ://codesandbox.io/s/react-select-ellipsis -one-row-example-k62hy

希望这足以解决问题或至少提供线索。


推荐阅读