显示页面的代码
<NavLink to='/home/daily/detail/ahe' > <Ahe >AHE测试</Ahe> </NavLink>
在style.js设置了一下Ahe的样式
export const Ahe = styled.div`
width: 100%;
height: 50px;
line-height:50px;
color:black;
text-align:center;
`;
最后想得到选中Ahe就改变样式成如下的效果
为了使用style-components来修改NavLink被选中时的样式,我们需要使用styled(NavLink)来定义我们的NavLink样式,并且使用CSS伪类选择器来设置选中时的样式。以下是代码示例:
import styled from 'styled-components';
import { NavLink } from 'react-router-dom';
export const StyledNavLink = styled(NavLink)`
width: 100%;
height: 50px;
line-height: 50px;
color: black;
text-align: center;
&:hover {
background-color: #ccc;
color: white;
}
&.active {
background-color: #007bff;
color: white;
font-weight: bold;
}
`;
在这个示例中,我们首先导入style-components和NavLink组件,然后使用styled(NavLink)来定义一个新的组件StyledNavLink,并设置样式,包括默认样式和:hover伪类的样式。最后,我们使用&.active伪类来设置选择时的样式。
最后,在我们的代码中,我们需要使用这个新组件来代替原始的NavLink组件:
<StyledNavLink to='/home/daily/detail/ahe' > AHE测试 </StyledNavLink>
这样,当NavLink被选中时,将会应用.active样式。