React Router v6结合Styled Components封装激活态NavLink失效如何解决
问题原因
React Router v6 的 NavLink 与 Styled Components 配合时,会自动将激活态相关状态(isActive、isPending、isTransitioning)作为 props 传递给 Styled 生成的样式函数,不需要通过 style 属性手动传递逻辑。你打印 props.style 为 undefined 是因为替换为自定义组件后没有传入对应 style 属性,且将激活态逻辑耦合在 style 属性内的写法不符合两个库的配合规范。
正确实现方案
封装自定义StyledNavLink
直接在样式模板中读取自动传入的isActive属性判断激活态即可:
import { styled } from 'styled-components'; import { NavLink } from 'react-router-dom'; const StyledNavLink = styled(NavLink)` text-decoration: ${props => props.isActive ? "underline" : "none"}; &:hover { text-decoration: underline; } `;
业务代码中使用
直接替换所有原有NavLink,无需重复编写激活态样式逻辑,原有end等原生属性仍可正常传递:
export default function BasicExample() { return ( <Router> <Navbar> <NavItems> <NavItem> <StyledNavLink to="/" end={true}> Home </StyledNavLink> </NavItem> <NavItem> <StyledNavLink to="/about"> About </StyledNavLink> </NavItem> <NavItem> <StyledNavLink to="/dashboard"> Dashboard </StyledNavLink> </NavItem> </NavItems> </Navbar> <Routes> <Route path="/" caseSensitive={false} element={<Home />} /> <Route path="/about" caseSensitive={false} element={<About />} /> <Route path="/dashboard" caseSensitive={false} element={<Dashboard />} /> </Routes> </Router> ); }
扩展能力
如果需要部分场景禁用激活态下划线,可新增自定义prop实现灵活控制:
const StyledNavLink = styled(NavLink)` text-decoration: ${props => props.disableActiveUnderline ? "none" : (props.isActive ? "underline" : "none")}; &:hover { text-decoration: underline; } `; // 使用时传入prop即可 <StyledNavLink to="/custom" disableActiveUnderline>自定义链接</StyledNavLink>
内容的提问来源于stack exchange,提问作者Sangeet Agarwal
相关产品推荐
相关产品推荐

