You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在React JS中返回通过createElement创建的自定义HTML div?

How to render a DOM element created with document.createElement() in a React class component?

Hey, let's break down why your code is throwing that error and how to fix it!

First, the error message says it clearly: React doesn't accept raw native DOM elements (like your HTMLDivElement) as children directly. When you return the div you created with document.createElement(), you're passing React a real browser DOM object—but React expects React elements (the objects generated by JSX or React.createElement() calls) instead. That's why your attempt to render it fails, even though console.log(div) shows the element exists.

Here are two ways to solve this:

Solution 1: Use JSX (the standard React approach)

Instead of manually building DOM elements with vanilla JS, use JSX to describe your UI structure. This aligns with React's declarative philosophy and plays seamlessly with its rendering system.

Here's how to rewrite your component:

import React, { Component } from 'react';

class Main extends Component {
  renderList() {
    // Return a React element (JSX) instead of a native DOM node
    return (
      <div>
        <ul>
          {/* Add list items here, e.g., by mapping over data: */}
          {/* {this.props.listItems.map(item => (
            <li key={item.id}>{item.content}</li>
          ))} */}
        </ul>
      </div>
    );
  }

  render() {
    return (
      <div>
        {this.renderList()}
      </div>
    );
  }
}

export default Main;

This works because JSX compiles to React.createElement() calls, which produce plain JavaScript objects that React understands. React will handle converting these objects into actual DOM elements for you.

Solution 2: Mount the native DOM element via a ref (for edge cases)

If you absolutely need to use document.createElement() (like integrating with a non-React library that generates DOM nodes), you can use a React ref to attach your custom element to the DOM after the component mounts.

Here's the code for this approach:

import React, { Component } from 'react';

class Main extends Component {
  constructor(props) {
    super(props);
    // Create a ref to hold our container element
    this.listContainer = React.createRef();
  }

  componentDidMount() {
    // Create your native DOM elements here
    const div = document.createElement("div");
    const ul = document.createElement("ul");

    // Optional: Add content to the list
    const sampleItem = document.createElement("li");
    sampleItem.textContent = "My custom list item";
    ul.appendChild(sampleItem);

    div.appendChild(ul);

    // Attach the created div to the ref's DOM node
    if (this.listContainer.current) {
      this.listContainer.current.appendChild(div);
    }
  }

  render() {
    // Render an empty container to mount our custom DOM into
    return (
      <div>
        <div ref={this.listContainer}></div>
      </div>
    );
  }
}

export default Main;

Here, we use a ref to access a container element that React renders. In componentDidMount() (which runs after the component is mounted to the browser DOM), we create our native elements and append them to the container. This works because we're letting React handle the initial render, then inserting our custom DOM into its managed container.

Quick note

Unless you have a specific requirement for raw DOM manipulation, Solution 1 is always the best choice for React code. It keeps your code consistent with React's patterns and avoids conflicts with React's reconciliation process.

内容的提问来源于stack exchange,提问作者suuuustt

火山引擎 最新活动