繁体   English   中英

尝试在render()中返回Node时,“对象作为React子无效”

[英]“Objects are not valid as a React child” when trying to return a Node inside render()

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

export class OverworldComponent extends React.Component<OverworldComponentProps, {}> {
    render() {
        return <b>Hello, world!</b>
    }
}

世界,而不是你好! 但是,我想在页面上输出HTMLElement的副本。 (具体来说是一张桌子。)

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

这会编译,但会导致以下错误(Chrome检查器):

在此处输入图片说明

而且,仅仅寻找将我的HTMLTableElement“投射”到与React兼容的东西的感觉是不合适的。 当我尝试使用<HTMLElement>进行强制转换时,它会将其解释为标记(缺少结束标记)而不是强制转换。 所以我一定不明白render() 我认为框架中应该做些不同的事情,但是我不知道该怎么做。

就上下文而言,我正处于将于明天结束的黑客马拉松中,而我今天开始学习React和Typescript,因此我缺少很多知识(根本没有任何经验)。

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是一个prop,其值是一个对象:

{ __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与innerHTML和textContent。 如何选择?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM