我有导航链接列表:
const users = Array.from(Array(5).keys()).map((key) => ({
id: key,
name: `User ${key}`,
}));
<List>
{users.map((user) => {
return (
<ListItem disablePadding key={user.id}>
<ListItemButton
component={NavLink}
to={`/messages/${user.id}`}
sx={{
"&.active": {
backgroundColor: "lightgray",
},
}}
>
<ListItemIcon>
<PersonIcon />
</ListItemIcon>
<ListItemText primary={user.name}></ListItemText>
</ListItemButton>
</ListItem>
);
})}
</List>
问题是我必须手动指定活动链接的样式并硬编码backgroundColor
。当我从组件中删除sx
样式时,链接看起来不像是活动的。为什么它在活动时不自动改变背景颜色?
1条答案
按热度按时间mspsb9vt1#
ListItemButton
扩展了基本按钮组件,这两个组件都没有用于添加"active"
CSS类名的任何默认样式。当 * 实际 * 将NavLink
组件 * 呈现为 *ListItemButton.component
时,NavLink
组件应用"active"
类,但默认链接样式被基本按钮和ListItemButton
样式覆盖/设置。NavLink
***默认情况下,
active
类在<NavLink>
组件处于活动状态时添加到该组件。***这为大多数从v5升级的用户提供了相同的简单样式机制。与v6.0.0-beta.3
的一个区别是,activeClassName
和activeStyle
已从NavLinkProps
中删除。相反,您可以向style
或className
传递一个函数,该函数允许您根据组件的活动状态自定义内联样式或类字符串。默认背景色为
"transparent"
,"active"
将覆盖它。ListItemButton
的sx
属性为"active"
类设置样式,并具有更高的CSS选择器特异性。另一种为
ListItemButton
/NavLink
应用CSS的方法是使用NavLink
的style
函数prop: