如何以编程方式 'open' Material-UI Select 字段?

How does one programmatically 'open' a Material-UI Select field?

可以在此处找到 select 字段:in the Material-UI demo

它的方法似乎是从菜单/弹出窗口继承的 类 但我一直无法弄清楚如何触发 'open' 例如,当 onFocus 事件触发时。这将解决我与键盘相关的可用性问题!

您可以通过访问向下箭头按钮的 DOM 节点,并在其上手动触发点击事件来实现。

在演示网站上 Mac Chrome 上运行的示例,通过控制台,在 select 字段中添加 'mySelect' id 字段后 DOM 元素以便于访问:

// Initialize a click event (mouseup seem more cross browser)
var evt = document.createEvent('MouseEvents');
evt.initEvent('mouseup', true, false);
// The down arrow elment is the only SVG element un the select
var elm = document.querySelector('#mySelect svg')
// Dispatch the event (reusable)
elm.dispatchEvent(evt);

如果此解决方案适合您的代码,您必须检查完整交叉 browser/platform 方法来创建正确的事件,并且 select 箭头元素(querySelector 是并非随处可用,尽管 it's quite OK now)

看例子https://material-ui.com/components/selects/#controlled-open-select

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles((theme) => ({
  button: {
    display: 'block',
    marginTop: theme.spacing(2),
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120,
  },
}));

export default function ControlledOpenSelect() {
  const classes = useStyles();
  const [age, setAge] = React.useState('');
  const [open, setOpen] = React.useState(false);

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

  const handleClose = () => {
    setOpen(false);
  };

  const handleOpen = () => {
    setOpen(true);
  };

  return (
    <div>
      <Button className={classes.button} onClick={handleOpen}>
        Open the select
      </Button>
      <FormControl className={classes.formControl}>
        <InputLabel id="demo-controlled-open-select-label">Age</InputLabel>
        <Select
          labelId="demo-controlled-open-select-label"
          id="demo-controlled-open-select"
          open={open}
          onClose={handleClose}
          onOpen={handleOpen}
          value={age}
          onChange={handleChange}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}