簡體   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