React应用中按钮内嵌入SVG报错:<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
相关产品推荐
相关产品推荐

