在 React 中渲染 HTMLDivElement

Posted

技术标签:

【中文标题】在 React 中渲染 HTMLDivElement【英文标题】:Render HTMLDivElement in React 【发布时间】:2016-12-10 11:08:11 【问题描述】:

我在尝试使用 React 渲染 htmlDivElement 时遇到了这个问题,但是我收到以下错误:

Uncaught Invariant Violation: Objects are not valid as a React child (found: [object HTMLDivElement]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `VirtualList`

在我的 React Component 类中,我有这段代码...

import React,  Component  from 'react';

export default class VirtualList extends Component 

    constructor(props) 
        super(props);

        this.container = document.createElement('div');
    

    renderList() 
        let container = this.container;

        // Manipulate container etc.

        return container;
    

    render() 

        return (
            <div>
                this.renderList()
            </div>
        )
    

我们将不胜感激!

【问题讨论】:

你能解释一下为什么要使用document.createElement吗? 处理dom不是react方式。 @AlexanderT。我写了一些简单的 javascript 代码,背后有一堆逻辑,所以我想在某种意义上将该代码移植到 React 中,认为你可以只渲染 HTMLDivElement 对象 【参考方案1】:

DOCS:

ReactElements 不要与 DOM 元素混淆。

你可以通过 React.createElement 创建 React Element。

this.container = React.createElement('div');

【讨论】:

【参考方案2】:

有点晚了,但我偶然发现了同样的问题。

您可以修改代码以创建 div 的引用,然后可以将其视为普通的 HTML 元素。首先,创建 div:

constructor(props) 
        super(props);

        this.container = document.createElement('div');
        this.reference = React.createRef();
    

然后,将 ref 添加到正确的 div:

render() 

        return (
            <div ref=this.reference>
            </div>
        )
    

你可以随时追加,但我会在组件挂载后进行:

componentDidMount()

    this.reference.current.appendChild(this.container());


请参阅here 以了解具有功能组件的实现

【讨论】:

以上是关于在 React 中渲染 HTMLDivElement的主要内容,如果未能解决你的问题,请参考以下文章

在 React 中渲染父组件

在 React 中渲染 HTMLDivElement

在 React 中重新渲染条件渲染组件

react渲染原理分析

如何在react中渲染原始的html文档

如何在 React/redux 中进行服务器端渲染?