reactjs ListItemButton as NavLink -活动/选定时应用样式

n1bvdmb6  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(110)

我有导航链接列表:

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样式时,链接看起来不像是活动的。为什么它在活动时不自动改变背景颜色?

mspsb9vt

mspsb9vt1#

ListItemButton扩展了基本按钮组件,这两个组件都没有用于添加"active" CSS类名的任何默认样式。当 * 实际 * 将NavLink组件 * 呈现为 * ListItemButton.component时,NavLink组件应用"active"类,但默认链接样式被基本按钮和ListItemButton样式覆盖/设置。
NavLink

***默认情况下,active类在<NavLink>组件处于活动状态时添加到该组件。***这为大多数从v5升级的用户提供了相同的简单样式机制。与v6.0.0-beta.3的一个区别是,activeClassNameactiveStyle已从NavLinkProps中删除。相反,您可以向styleclassName传递一个函数,该函数允许您根据组件的活动状态自定义内联样式或类字符串。

默认背景色为"transparent""active"将覆盖它。

ListItemButtonsx属性为"active"类设置样式,并具有更高的CSS选择器特异性。
另一种为ListItemButton/NavLink应用CSS的方法是使用NavLinkstyle函数prop:

<List>
  {users.map((user) => {
    return (
      <ListItem disablePadding key={user.id}>
        <ListItemButton
          component={NavLink}
          to={`/messages/${user.id}`}
          style={({ isActive }) => isActive ? {
            backgroundColor: "lightgray"
          } : null}
        >
          <ListItemIcon>
              <PersonIcon />
          </ListItemIcon>
          <ListItemText primary={user.name}></ListItemText>
        </ListItemButton>
      </ListItem>
    );
  })}
</List>

相关问题