You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改React Navbar组件中react-router-dom Link标签的文字颜色?

解决styled-components中react-router-dom Link样式不生效的问题

问题核心在于react-router-dom的Link最终会渲染为原生<a>标签,浏览器对<a>标签有默认样式(默认蓝色、带下划线),且父元素的color属性不会自动继承到<a>标签上,所以直接在父容器、ul或li里设置样式无法生效。下面提供两种简单有效的解决方法:

方法一:在父样式中直接选中<a>标签(推荐)

直接在Nav的样式规则里,针对li下的<a>标签设置样式,覆盖浏览器默认样式:

const Nav = styled.div`
  height: 70px;
  width: 100%;
  background-color: black;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 30px;

  ul {
    display: flex;
    list-style: none;
    
    li {
      margin: 0 20px;
      font-size: 20px;

      // 直接选中Link渲染后的a标签
      a {
        color: white;
        text-decoration: none; // 去掉默认下划线

        // 可选:添加hover交互效果
        &:hover {
          color: red;
          text-decoration: underline;
        }
      }
    }
  }
`

方法二:用styled-components包装Link组件

创建一个自定义的StyledLink组件,直接给它设置样式,替换原有的Link:

import React from 'react'
import styled from 'styled-components';
import {Link} from 'react-router-dom'

// 用styled包装Link
const StyledLink = styled(Link)`
  color: white;
  font-size: 20px;
  margin: 0 20px;
  text-decoration: none;

  &:hover {
    color: red;
    text-decoration: underline;
  }
`

const Navbar = () => {
  return (
    <>
    <Nav>
      <Title>
        PortFolio
      </Title>
      <ul>
        <li><StyledLink to='/'>Home</StyledLink></li>
        <li><StyledLink to='/contact'>Contact</StyledLink></li>
      </ul>
    </Nav>
    </>
  )
}

export default Navbar

const Nav = styled.div`
  height: 70px;
  width: 100%;
  background-color: black;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 30px;

  ul {
    display: flex;
    list-style: none;
    
    li {
      list-style: none;
    }
  }
`
const Title = styled.span`
  font-size: 40px;
  font-family: 'Ubuntu', sans-serif; 
`

两种方法都能解决你的问题,方法一适合快速修改现有样式,方法二更适合需要复用带样式的Link组件的场景。

内容的提问来源于stack exchange,提问作者Aditya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:45:35