【问题标题】:Disable "Select By Typing" in Material UI Menu Component在 Material UI 菜单组件中禁用“通过键入选择”
【发布时间】:2021-06-10 02:35:09
【问题描述】:

我正在尝试制作一个弹出菜单,其中包含几个不同的过滤器(按钮、选择和文本字段)。我正在使用 Material UI Menu 组件,但在尝试使用文本字段时遇到了问题。因为 Menu 组件的行为类似于 <Select />,所以当我在文本字段中键入内容时,它会尝试选择不同的 MenuItem,而不是一直专注于文本框。

因此,使用下面沙箱中的示例,如果“搜索其他食物”文本框以“A”、“B”或“C”开头,用户将无法在该文本框中输入任何内容。如果您想输入“杏子”,菜单会将焦点从文本框更改为“Apples”菜单项。

我在 Menu API 中没有看到任何关于此的道具,所以我很想知道是否有任何变通方法,甚至是更适合此的不同组件。

谢谢!

这是一个代码框:https://codesandbox.io/s/wizardly-mccarthy-zy2b7

import { useState } from "react";
import "./styles.css";
import { Button, Menu, MenuItem, TextField } from "@material-ui/core";

export default function App() {
  const [menu, setMenu] = useState(null);
  const [text, setText] = useState("");

  return (
    <div className="App">
      <Button variant="outlined" onClick={(e) => setMenu(e.currentTarget)}>
        Filters
      </Button>

      <Menu
        anchorEl={menu}
        open={Boolean(menu)}
        getContentAnchorEl={null}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "left"
        }}
        onClose={() => setMenu(null)}
      >
        <MenuItem>Apples</MenuItem>
        <MenuItem>Bananas</MenuItem>
        <MenuItem>Carrots</MenuItem>
        <MenuItem>
          <TextField
            value={text}
            onChange={(e) => setText(e.target.value)}
            variant={"outlined"}
            label={"search a different food..."}
          />
        </MenuItem>
      </Menu>
    </div>
  );
}

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    在包含 TextField 的 MenuItem 的 onKeyDown 事件中使用 e.stopPropagation()。这将防止按键事件传播到 Menu 组件。

        <MenuItem onKeyDown={(e) => e.stopPropagation()}>
            <TextField
                value={text}
                onChange={(e) => setText(e.target.value)}
                variant={"outlined"}
                label={"search a different food..."}
            />
        </MenuItem>
    

    参考:How to disable the selection of an item when the first letter of the option is pressed in the Select component?

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2021-05-12
      • 2021-06-05
      • 2017-12-30
      • 1970-01-01
      相关资源
      最近更新 更多