我正在使用 React 制作一个网站。
当我的网站有很多文本时,我会显示一个按钮,例如show more or less
.
在我的项目中,它运行良好,但总是显示警告validateDOMNesting(...): <button>
我的示例代码是这样的。
const [show, setShow] = useState(false);
function handleShow() {
show ? setShow(false) : setShow(true);
}
<CardActionArea>
<Button onClick={handleShow}>
{ show ? text : text.substr(0, 100) + "..." }
</Button>
</CardActionArea>
I think CardActionArea
is a button
组件,它使一个嵌套button
now.
但如果我声明href
财产在button
,它不会发出警告。
有没有一个好的方法,不发出警告不使用href
财产?
Issue:在您的代码中,您已经在按钮中放置了一个按钮,这是不允许的。
来自Material-UI CardActionAreadocs https://material-ui.com/api/card-action-area/#inheritance
遗产
的道具ButtonBase
组件也可用。你可以采取
利用此行为来定位嵌套组件。
如果你继续航行到按钮底座 https://material-ui.com/api/button-base/#component-name你会看到它默认是一个文档'button'
成分。
选项1:将按钮逻辑移至CardActionArea
并设置component
的支柱Button
对任何事not一个按钮,就像一个跨度。这使得整个卡片操作区域都有 onClick 处理程序并且具有响应性。
<CardActionArea onClick={handleShow}>
<Button component="span">
{ show ? text : text.substr(0, 100) + "..." }
</Button>
</CardActionArea>
选项2:保持原样并设置组件的 propCardActionArea
to 其他任何东西比“按钮”。这将离开only具有 onClick 处理程序的按钮,卡片操作区域将记录点击,即连锁反应,但否则将无响应。
<CardActionArea component="span">
<Button onClick={handleShow}>
{ show ? text : text.substr(0, 100) + "..." }
</Button>
</CardActionArea>
两者之间option 1在我看来,这是首选选项,因为它使整个行动区域具有响应性,但这完全基于所提供的事实,并且您的需求/设计可能会有所不同或更复杂。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)