尝试在render()内返回一个Node时,“对象无法作为React子对象”

时间:2018-03-16 01:21:15

标签: javascript reactjs typescript dom

我在页面上显示以下内容:

export class OverworldComponent extends React.Component<OverworldComponentProps, {}> {
    render() {
        return document.querySelector('div.file div.data table').cloneNode(false);
    }
}

而不是 Hello,world!,我想在页面上输出一个HTMLElement的克隆。 (一张表,具体而言。)

<HTMLElement>

这会编译但会导致以下错误(Chrome Inspector):

enter image description here

仅仅寻找将HTMLTableElement“强制转换”为React兼容的方法并不合适。当我尝试使用render()进行投射时,它将其解释为标记(缺少结束标记)而不是强制转换。所以我不能理解{{1}}中的机制是什么。我认为在框架中我应该采用不同的方式,但我不知道是什么。

对于上下文,我正处于明天结束的黑客马拉松之中,今天我开始学习React和Typescript,所以我缺少很多知识(并且缺乏任何经验)。

1 个答案:

答案 0 :(得分:1)

document.querySelector('div.file div.data table').cloneNode(false);是纯Web API。这意味着它返回了DOM节点,而不是React Component。

React Component的子节点也必须是React Component。

如果要将DOM节点注入React组件,请考虑使用dangerouslySetInnerHTML https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

详细信息:

dangerouslySetInnerHTML是一个道具,它的值是一个对象:

{ __html: '<p>a chunk of html source code</p>' }

在您的情况下,可能是:

{ __html: document.querySelector('div.file div.data table').innerHtml }

{ __html: document.querySelector('div.file div.data table').textContent }

您还可以使用nodeValueinnerText

请阅读此处以查看差异并选择最佳差异: nodeValue vs innerHTML and textContent. How to choose?