不能显示为

的后代

reactjs React.js

TonyDavaidLEY

2020-03-14

我看到了 它抱怨的不是什么谜:

Warning: validateDOMnesting(...): <div> cannot appear as a descendant of <p>. See ... SomeComponent > p > ... > SomeOtherComponent > ReactTooltip > div.

我的作者SomeComponentSomeOtherComponent但是后者正在使用外部依赖项(ReactTooltipfrom react-tooltip)。这可能不是一个外部依赖关系,但这不是必须的,但是它让我在这里尝试说“这是我无法控制的某些代码”。

考虑到嵌套组件工作正常(貌似),我应该为这个警告感到多担心?而且无论如何我将如何进行更改(前提是我不想重新实现外部依赖项)?是否有我尚未意识到的更好的设计?

为了完整起见,这里是的实现SomeOtherComponent它只是呈现this.props.value,并且在悬停时:提示“某些工具提示消息”的工具提示:

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>
  }
}

谢谢。

</div>

第1608篇《

不能显示为

的后代》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
樱Tony 2020.03.14

我遇到了类似的问题,将组件包装在“ div”而不是“ p”中,错误消失了。

猿小宇宙小哥 2020.03.14

您的组件可能在另一个组件(例如<Typography> ... </Typography>)中呈现因此,它会将您的组件加载到<p> .. </p>不允许的内部

修复:删除,<Typography>...</Typography>因为这仅用于a <p>...</p>或任何其他文本元素(例如标题)中的纯文本

Monkey洋 2020.03.14

根据警告消息,组件ReactTooltip呈现可能如下所示的HTML:

<p>
   <div>...</div>
</p>

According to this document, a <p></p> tag can only contain inline elements. That means putting a <div></div> tag inside it should be improper, since the div tag is a block element. Improper nesting might cause glitches like rendering extra tags, which can affect your javascript and css.

If you want to get rid of this warning, you might want to customize the ReactTooltip component, or wait for the creator to fix this warning.

达蒙Green逆天 2020.03.14

如果您正在寻找发生这种情况的地方,则可以在控制台中使用: document.querySelectorAll(" p * div ")

LEY猿 2020.03.14

如果您使用ReactTooltip,要使警告消失,现在可以添加wrapper值为的道具span,如下所示:

<ReactTooltip wrapper="span" />

由于span是内联元素,因此不应再抱怨。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android