如何使用样式化组件在Next.JS中创建活动链接 [英] How to make active Links in Next.JS using styled-components
本文介绍了如何使用样式化组件在Next.JS中创建活动链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个副项目中创建了一个简单的导航栏,在Next.JS中遇到了活动链接的问题,在REACTION中,您可以只使用Reaction-Router-dom,它有一个带有active类属性的Link组件,但在Next.JS(我想)中没有。
推荐答案
为使其正常工作,我使用了UseRouter
UseState
钩子
const router = useRouter();
const [pathName, setPathName] = useState(router.pathname);
router.pathname正在获取您的url中当前的/[route]
内容。
const newPathName = () => {
setPathName(router.pathname);
};
<Link href="/" passHref>
<StyledLink onClick={newPathName} pathname={pathName}>
Home
</StyledLink>
</Link>
通过将其用作onclick函数,它将useState设置为新路由
StyledLink将是单击时将更改颜色的样式组件
export const StyledLink = styled.a`
color: ${(props) => (props.href === props.pathname ? "#a37600" : "#eaaa00")};
text-decoration: none;
padding-top: 20px;
font-size: 1.3rem;
:hover {
text-decoration: underline;
color: #a37600;
}
`;
我基本上是这样回答的,因为我搜索了大约30分钟,没有找到任何对于导航栏来说足够简单和快速的答案,如果有类似或更简单的答案,请链接到我。
这篇关于如何使用样式化组件在Next.JS中创建活动链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文