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

react-router-dom v6 Link搭配styled-components使用时页面不渲染

问题根因

react-router-dom v6 版本的Link组件最终会渲染为原生<a>标签,你当前代码将<button>元素直接嵌套在<a>标签内部,属于HTML规范不允许的非法嵌套结构,浏览器解析DOM时会自动纠错拆分节点,最终导致组件无法正常渲染、页面空白。

可行修复方案

你可以根据需求二选一:

  • 方案1:直接用styled-components包装Link组件,移除多余的button嵌套,把按钮样式直接应用在Link上,这是最推荐的写法
import styled from "styled-components";
import { Link } from "react-router-dom";

const Home = () => {
  return <HomeButton to="/">Place Order</HomeButton>;
};

const HomeButton = styled(Link)`
  /* 补充a标签需要的布局样式,保证和原按钮表现一致 */
  display: inline-block;
  text-align: center;
  line-height: 45px;
  text-decoration: none;
  /* 原有按钮样式保留 */
  color: black;
  font-weight: bold;
  font-family: "Space Grotesk", sans-serif;
  font-size: 1.2rem;
  background-color: white;
  height: 45px;
  border-radius: 5px;
  width: 86%;
  margin-left: 7%;
  margin-right: 7%;
  margin-top: 20px;
  -webkit-box-shadow: -1px 0px 2px 2px rgba(99, 99, 99, 1);
`;

export default Home;
  • 方案2:如果必须保留button元素,就不要嵌套Link,改用路由提供的useNavigate钩子绑定点击事件实现跳转
import styled from "styled-components";
import { useNavigate } from "react-router-dom";

const Home = () => {
  const navigate = useNavigate();
  return <HomeButton onClick={() => navigate("/")}>Place Order</HomeButton>;
};

const HomeButton = styled.button`
  /* 补充按钮默认样式重置 */
  border: none;
  cursor: pointer;
  /* 原有按钮样式保留 */
  color: black;
  font-weight: bold;
  font-family: "Space Grotesk", sans-serif;
  font-size: 1.2rem;
  background-color: white;
  height: 45px;
  border-radius: 5px;
  width: 86%;
  margin-left: 7%;
  margin-right: 7%;
  margin-top: 20px;
  -webkit-box-shadow: -1px 0px 2px 2px rgba(99, 99, 99, 1);
`;

export default Home;
额外提醒
  • 永远不要在<a>标签内嵌套<button>、<a>这类可交互元素,属于无效HTML结构,会触发浏览器的DOM自动纠错,引发各种不可预期的渲染问题
  • styled-components支持直接包装任意可接收className属性的组件,写法为styled(目标组件),不需要额外增加嵌套标签层

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:54:26