<div>不能作为 <p> 的后代出现 [英] <div> cannot appear as a descendant of <p>
问题描述
我看到了这个.它在抱怨什么并不神秘:
警告:validateDOMnesting(...): 不能作为 <p> 的后代出现.见 ... SomeComponent >≥... >其他组件 >反应工具提示 >分区我是 SomeComponent
和 SomeOtherComponent
的作者.但后者使用的是外部依赖(ReactTooltip
来自 react-tooltip代码>
).这是一个外部依赖项可能并不重要,但它让我在这里尝试论证它是一些不受我控制的代码".
鉴于嵌套组件工作正常(表面上),我应该如何担心这个警告?无论如何我将如何改变它(假设我不想重新实现外部依赖)?是否有我尚未意识到的更好的设计?
为了完整起见,这里是 SomeOtherComponent
的实现.它只是呈现 this.props.value
,当悬停时:一个工具提示,上面写着一些工具提示消息":
class SomeOtherComponent 扩展 React.Component {构造函数(道具){超级(道具)}使成为() {const {value, ...rest} = this.props;return <a href="#" data-tip="Some tooltip message" {...rest}>{value}</a><ReactTooltip/></span>}}
谢谢.
解决方案 如果在使用 Material UI 时出现这个错误
https://material-ui.com/api/typography/,那么你就可以很容易的把
改成a
通过改变
元素的 component
属性的值:
根据排版文档:
<块引用>component :用于根节点的组件.使用 DOM 元素或组件的字符串.默认情况下,它将变体映射到一个好的默认标题组件.
因此,Typography 选择
作为合理的默认值,您可以更改它.可能会带来副作用......对我有用.
I'm seeing this. It's not a mystery what it is complaining about:
Warning: validateDOMnesting(...): <div> cannot appear as a descendant of <p>. See ... SomeComponent > p > ... > SomeOtherComponent > ReactTooltip > div.
I'm the author of SomeComponent
and SomeOtherComponent
. But the latter is using an external dependency (ReactTooltip
from react-tooltip
). It's probably not essential that this is an external dependency, but it lets me try the argument here that it is "some code that's out of my control".
How worried should I be about this warning, given that the nested component is working just fine (seemingly)? And how would I go about changing this anyway (provided I don't want to re-implement an external dependency)? Is there maybe a better design that I'm yet unaware of?
For completeness sake, here's the implementation of SomeOtherComponent
. It just renders this.props.value
, and when hovered: a tooltip that says "Some tooltip message":
class SomeOtherComponent extends React.Component {
constructor(props) {
super(props)
}
render() {
const {value, ...rest} = this.props;
return <span className="some-other-component">
<a href="#" data-tip="Some tooltip message" {...rest}>{value}</a>
<ReactTooltip />
</span>
}
}
Thank you.
解决方案 If this error occurs while using Material UI <Typography>
https://material-ui.com/api/typography/, then you can easily change the <p>
to a <span>
by changing the value of the component
attribute of the <Typography>
element :
<Typography component={'span'} variant={'body2'}>
According to the typography docs:
component : The component used for the root node. Either a string to use a DOM element or a component. By default, it maps the variant to a good default headline component.
So Typography is picking <p>
as a sensible default, which you can change. May come with side effects ... worked for me.
这篇关于<div>不能作为 <p> 的后代出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文