在寻找指定了htmlFor
的标签后,我正在寻找一种从Material UI中打开Select(非本机)组件的方法。
<label htmlFor='menu'>Label to open Menu</label>
<MUISelect inputProps={{id: 'menu'}} native={false}>{options}</MUISelect>
显然不起作用
答案 0 :(得分:1)
此问题有两个主要方面:
id
放置在具有用于打开菜单的点击处理程序的元素上。div
,而不是input
。当标签元素不是输入元素时,标签不会自动触发其事件。可以使用SelectDisplayProps
解决第一个方面:
SelectDisplayProps={{ id: "menu" }}
第二个方面可以通过自定义标签组件解决:
import React from "react";
const LabelForClickableDiv = ({ htmlFor, ...other }) => {
const onClick = () => {
document.getElementById(htmlFor).click();
};
return <label htmlFor={htmlFor} onClick={onClick} {...other} />;
};
export default LabelForClickableDiv;
这是一个可行的示例:
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
import LabelForClickableDiv from "./LabelForClickableDiv";
const useStyles = makeStyles(theme => ({
root: {
display: "flex",
flexWrap: "wrap"
},
formControl: {
margin: theme.spacing(1),
minWidth: 120
},
selectEmpty: {
marginTop: theme.spacing(2)
}
}));
function SimpleSelect() {
const classes = useStyles();
const [value, setValue] = React.useState("");
return (
<>
<form className={classes.root} autoComplete="off">
<FormControl className={classes.formControl}>
<LabelForClickableDiv htmlFor="menu">
Label to open Menu
</LabelForClickableDiv>
<Select
value={value}
onChange={event => {
setValue(event.target.value);
}}
SelectDisplayProps={{
id: "menu"
}}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</form>
</>
);
}
export default SimpleSelect;