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

React应用中按钮内嵌入SVG报错:<button>不能作为<button>的后代元素

解决React中<button>不能作为<button>后代的错误

问题原因

你导入的LogoutIconSvg组件内部渲染了一个<button>元素,外层的<button>和它形成嵌套,违反了HTML规范——button元素不能包含其他button元素,因此触发了validateDOMNesting错误。

解决方案

1. 直接修改SVG源文件(推荐)

打开../../assets/svg/logout-user.svg,找到其中的<button>标签,将其替换为<g>(SVG分组标签),或者直接移除包裹的交互标签,只保留SVG的图形路径等元素。

示例修改前的SVG片段:

<button class="icon-btn">
  <path d="..." />
</button>

修改后:

<g>
  <path d="..." />
</g>

2. 在代码中覆盖组件内部的button(临时方案)

如果无法修改SVG文件,可以通过React的cloneElement和Children.map来替换内部的button元素:

import React from 'react';
import { ReactComponent as LogoutIconSvg } from "../../assets/svg/logout-user.svg";

<button type="button" className={styles.profilemenu__item} style={{ "--icon": "#F94687 " }} onClick={logout}>
    {React.cloneElement(<LogoutIconSvg />, {
      children: React.Children.map(<LogoutIconSvg />.props.children, child => {
        // 识别并替换内部的button标签为span
        if (child.type === 'button') {
          return React.createElement('span', {}, child.props.children);
        }
        return child;
      })
    })}
    Logout
</button>

内容的提问来源于stack exchange,提问作者Ghayas Ud Din

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:39:34