如何使用 mui styled() 将样式应用到 NavLink 元素的活动链接?

问题描述 投票:0回答:2

我有一个 NavLink 包装组件。我想在该组件激活时为其添加

.active
样式,但我不知道如何使用
styled()
来完成。如何才能实现这一目标?

这是我的代码:

import { forwardRef } from "react";
import { NavLink as NavLinkBase } from "react-router-dom";
import { styled } from "@mui/system";


const NavLink = forwardRef((props, ref) => {
  return (
    <NavLinkBase   
      ref={ref}
      {...props}
      className={({ isActive }) => [
        props.className,
        isActive ? 'active' : null,
      ]
        .filter(Boolean)
        .join(" ")
      }
      end={props.to === '/' ? true : false}
    />  
  )
});

export default NavLink
javascript reactjs material-ui react-router react-router-dom
2个回答
5
投票

NavLink
组件处于活动状态时,默认情况下有一个
"active"
类名。用最简单的术语来说,您可以执行以下操作来定义 CSS/样式。

const NavLink = styled(NavLinkBase)(({ theme }) => ({
  ... default styling ...

  "&.active": {
    ... active styling ...
  }
}));

如果您还想定义一些默认 props,例如

end
prop 逻辑,那么创建一个匿名函数组件。

const NavLink = styled(props => (
  <NavLinkBase {...props} /* set default props here */ />
))(({ theme }) => ({
  ... default styling ...

  "&.active": {
    ... active styling ...
  }
}));

示例:

const NavLink = styled((props) => (
  <NavLinkBase {...props} end={props.to === "/"} />
))(({ theme }) => ({
  textDecoration: "none",

  "&.active": {
    color: "green",
    fontSize: theme.spacing(3)
  }
}));

...

<ul>
  <li>
    <NavLink to="/">Home</NavLink>
  </li>
  <li>
    <NavLink to="/foo">Foo</NavLink>
  </li>
  <li>
    <NavLink to="/bar">Bar</NavLink>
  </li>
</ul>

Edit how-to-apply-a-style-to-the-active-link-of-a-navlink-element-using-mui-styled


0
投票

您还可以使用

AppBar
Toolbar
来实现这一点。

我就是这样做的:

 import { NavLink } from 'react-router-dom';
 import styled from '@emotion/styled';

  const ActiveLink = styled(NavLink)({
    '&.active': {
      color: '#edff00'
    }
  });


   <AppBar position="static">
      <Toolbar>
        <Button
          component={ActiveLink}
          to="/"
          color="inherit"
          startIcon={<LoginIcon />}
          sx={{ display: { xs: 'none', sm: 'flex' } }}
        >
          Login
        </Button>
        <Button
          component={ActiveLink}
          to="/register"
          color="inherit"
          startIcon={<AppRegistrationIcon />}
          sx={{ display: { xs: 'none', sm: 'flex' } }}
        >
          Register
        </Button>
      </Toolbar>
    </AppBar>

因此,我使用 MUI 中的

styled
来设计
NavLink
,然后将其用作
Button
的组件,从而使我能够直接定义我将导航到的路线(至“”)单击按钮。

© www.soinside.com 2019 - 2024. All rights reserved.