[英]How to align Material-UI Menu items?
我使用 material-ui 的菜單和菜單項構建了一個 select 下拉菜單,但我發現有一點奇怪:下拉菜單總是展開到框的左側,如下圖所示:
我嘗試在<MenuItem>
中使用alignItems
屬性,但它不起作用。
我的代碼如下所示。 有人可以幫我解決這個問題嗎? 我真的很感謝你的幫助!
<Menu
id="order-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
>
{options.map((option, index) => (
<MenuItem
key={option}
selected={index === selectedIndex}
onClick={(event) => handleMenuItemClick(event, index)}
>
{option}
</MenuItem>
))}
</Menu>
默認的 styles 控制它在ListItem
中,它指定justifyContent: 'flex-start' 。
您可以將其更改為右對齊:
const MenuItem = withStyles({
root: {
justifyContent: "flex-end"
}
})(MuiMenuItem);
這是一個完整的工作示例:
import React from "react";
import Button from "@material-ui/core/Button";
import Menu from "@material-ui/core/Menu";
import MuiMenuItem from "@material-ui/core/MenuItem";
import { withStyles } from "@material-ui/core/styles";
const MenuItem = withStyles({
root: {
justifyContent: "flex-end"
}
})(MuiMenuItem);
export default function SimpleMenu() {
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClick = event => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<Button
aria-controls="simple-menu"
aria-haspopup="true"
onClick={handleClick}
>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
>
<MenuItem onClick={handleClose}>1</MenuItem>
<MenuItem onClick={handleClose}>2</MenuItem>
<MenuItem onClick={handleClose}>3</MenuItem>
<MenuItem onClick={handleClose}>10</MenuItem>
<MenuItem onClick={handleClose}>20</MenuItem>
<MenuItem onClick={handleClose}>300</MenuItem>
</Menu>
</div>
);
}
相關文檔:
您可以使用此代碼來對齊菜單
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
transformOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
例子
<Menu
id="order-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
transformOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
style={{top: 170}} // you can set top position so that it will show under the selection
>
{options.map((option, index) => (
<MenuItem
key={option}
selected={index === selectedIndex}
onClick={(event) => handleMenuItemClick(event, index)}
>
{option}
</MenuItem>
))}
更靈活的解決您的問題,
在<MenuItem>
中使用<ListItemText>
以這種方式您可以設置元素的部分樣式。
<MenuItem onClick={handleClose}>
<ListItemText style={{ paddingRight: 50 }}>undo</ListItemText>
<ListItemText style={{ textAlign: "right" }}>ctrl+z</ListItemText>
</MenuItem>
示例: 右側的快捷方式提示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.