我正在使用material-ui react库来使用<FormControl>
,<Select>
和<MenuItem>
组件呈现一些Dropdown菜单。该下拉菜单的options数组很大,我想在下拉菜单上设置max-height,因此它不会变得很大。我目前正在努力做到这一点,正如我将在下面解释的那样。
使用material-ui的基本下拉列表:
const MenuValidNotes = ({
schedule,
indexTrack,
indexSchedule,
actionSetTrackScheduleItemNote,
}) => {
const listNotesMenu = () => (
ARRAY_VALID_NOTES.map((noteObj, i) => (
<MenuItem
value={noteObj.note}
key={`track-item-${indexTrack}-schedule-${indexSchedule}-note-${i}`}
onClick={() => actionSetTrackScheduleItemNote(indexTrack, indexSchedule, noteObj.midiNumber)}
>{noteObj.note}</MenuItem>
))
)
return(
<div>
<FormControl>
<InputLabel>Note</InputLabel>
<Select
defaultValue={noteValueToNoteObject(schedule.noteValue).note}
>
{listNotesMenu()}
</Select>
</FormControl>
</div>
)
}
我发现设置max-height的一种方法是在div中渲染
<Select>
的子代,为其指定一个类名,然后对其应用一些CSS。但是,
<Select>
组件要求其子级为<MenuItem>s
,因此,在周围加上<div>
会破坏value
属性,这意味着它将无法显示正确的值。 (在阅读Material-UI Select e.target.value is undefined时发现了这个问题) const listNotesMenu = () => (
ARRAY_VALID_NOTES.map((noteObj, i) => (
<div className="..."> // this div will break the 'value' of the Select component
<MenuItem ... />
</div>
))
)
因此,理想情况下,我希望能够控制其子项的值和最大高度。这有可能吗? select上的material-ui文档没有这样的示例,并且
<Select
组件的props列表不包含任何用于控制高度的字段。感谢您的帮助。(上面的屏幕截图显示了此问题。一个屏幕截图显示可以使用div包装器控制最大高度,但这会破坏值;另一个屏幕截图显示了没有div包装器的下拉列表,这意味着我们无法设置max -heigh)。
最佳答案
您要控制的高度是Paper
中的Popover
元素呈现的Menu
元素。
default styles是maxHeight: 'calc(100% - 96px)'
。
下面是一个如何覆盖此示例:
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";
const useStyles = makeStyles(theme => ({
formControl: {
margin: theme.spacing(1),
minWidth: 120
},
selectEmpty: {
marginTop: theme.spacing(2)
},
menuPaper: {
maxHeight: 100
}
}));
const VALID_NOTES = [
"C",
"C#",
"D",
"D#",
"E",
"F",
"F#",
"G",
"G#",
"A",
"A#",
"B"
];
export default function SimpleSelect() {
const classes = useStyles();
const [note, setNote] = React.useState("");
const handleChange = event => {
setNote(event.target.value);
};
return (
<div>
<FormControl className={classes.formControl}>
<InputLabel id="demo-simple-select-label">Note</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={note}
onChange={handleChange}
MenuProps={{ classes: { paper: classes.menuPaper } }}
>
{VALID_NOTES.map(validNote => (
<MenuItem value={validNote}>{validNote}</MenuItem>
))}
</Select>
</FormControl>
</div>
);
}
关键方面是
MenuProps={{ classes: { paper: classes.menuPaper } }}
和menuPaper
样式的定义。
关于css - (material-ui)将最大高度应用于<Select>子代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61686939/