我正在使用 Material V5。如何设置所选列表项的样式?我想要 5px 的 borderLeft。
类似这样的事情:
const theme = createTheme({
palette: {
primary: {
// light: will be calculated from palette.primary.main,
main: colors.primary
// dark: will be calculated from palette.primary.main,
}
},
components: {
MuiListItem: {
styleOverrides: {
root: {
"&$selected": {
borderLeft: `5px solid ${colors.primary}`
}
}
}
}
}
});
这是我的代码和框:
import * as React from 'react';
import Box from '@material-ui/core/Box';
import List from '@material-ui/core/List';
import ListItemButton from '@material-ui/core/ListItemButton';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@material-ui/core/Divider';
import InboxIcon from '@material-ui/icons/Inbox';
import DraftsIcon from '@material-ui/icons/Drafts';
export default function SelectedListItem() {
const [selectedIndex, setSelectedIndex] = React.useState(1);
const handleListItemClick = (
event: React.MouseEvent<HTMLDivElement, MouseEvent>,
index: number,
) => {
setSelectedIndex(index);
};
return (
<Box sx={{ width: '100%', maxWidth: 360, bgcolor: 'background.paper' }}>
<List component="nav" aria-label="main mailbox folders">
<ListItemButton
selected={selectedIndex === 0}
onClick={(event) => handleListItemClick(event, 0)}
>
<ListItemIcon>
<InboxIcon />
</ListItemIcon>
<ListItemText primary="Inbox" />
</ListItemButton>
<ListItemButton
selected={selectedIndex === 1}
onClick={(event) => handleListItemClick(event, 1)}
>
<ListItemIcon>
<DraftsIcon />
</ListItemIcon>
<ListItemText primary="Drafts" />
</ListItemButton>
</List>
<Divider />
<List component="nav" aria-label="secondary mailbox folder">
<ListItemButton
selected={selectedIndex === 2}
onClick={(event) => handleListItemClick(event, 2)}
>
<ListItemText primary="Trash" />
</ListItemButton>
<ListItemButton
selected={selectedIndex === 3}
onClick={(event) => handleListItemClick(event, 3)}
>
<ListItemText primary="Spam" />
</ListItemButton>
</List>
</Box>
);
}
最佳答案
您的覆盖存在两个问题:
- 您在代码中使用
ListItemButton
而没有ListItem
这很好,但是您需要使用MuiListItemButton
而不是MuiListItem
为主题中的组件名称。 - 您使用了
“&$selected”
来引用选定状态,但这应该是“&.Mui-selected”
。
来自https://mui.com/guides/migration-v4/#migrate-themes-styleoverrides-to-emotion :
Although your style overrides defined in the theme may partially work, there is an important difference on how the nested elements are styled. The $ syntax used with JSS will not work with Emotion. You need to replace those selectors with a valid class selector.
这是工作版本的样子:
const theme = createTheme({
palette: {
primary: {
// light: will be calculated from palette.primary.main,
main: colors.primary
// dark: will be calculated from palette.primary.main,
}
},
components: {
MuiListItemButton: {
styleOverrides: {
root: {
"&.Mui-selected": {
borderLeft: `5px solid ${colors.primary}`
}
}
}
}
}
});
关于reactjs - 选定列表项的样式 Material UI V5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68639519/