如何以编程方式“打开” Material-UI Select 字段?

IT技术 inheritance reactjs material-ui
2021-05-23 13:51:26

可以在此处找到选择字段:在 Material-UI 演示中

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

2个回答

看例子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>
  );
}

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

在演示网站上通过控制台在 Mac Chrome 上运行的示例,在将“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);

如果此解决方案适合您的代码,则您必须检查完整的跨浏览器/平台方式来创建适当的事件,并选择箭头元素(querySelector并非随处可用,尽管现在已经可以了