You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用gridjs-react出现容器非空错误,寻求解决方法

问题:gridjs-react 报错容器非空

错误信息

[Grid.js] [ERROR]: The container element [object HTMLDivElement] is not empty. Make sure the container is empty and call render() again

代码示例

import React from 'react'
import { Grid } from "gridjs-react";
import "gridjs/dist/theme/mermaid.css";


const Grid1 = () => {
    return (
        <Grid
            data = {[
                ['John', 'john@example.com'],
                ['Mike', 'mike@gmail.com']
                ]}
            columns = {['Name', 'Email']}
            search = {true}
            sort={true}
        />
    )
}

export default Grid1

解决办法

  • 检查父容器内容:确保渲染Grid组件的父DOM元素是空的,清理掉其中的文本、空格、注释或其他子元素。

  • 添加唯一key强制重新渲染:如果是React热重载或组件重复渲染导致旧内容残留,给Grid组件添加唯一key,确保每次渲染创建新实例:

    <Grid
        key={Date.now()}
        data={[
            ['John', 'john@example.com'],
            ['Mike', 'mike@gmail.com']
        ]}
        columns={['Name', 'Email']}
        search={true}
        sort={true}
    />
    
  • 手动清理容器(进阶):若上述方法无效,可在组件挂载前手动清空容器:

    import React, { useEffect, useRef } from 'react'
    import { Grid } from "gridjs-react";
    import "gridjs/dist/theme/mermaid.css";
    
    const Grid1 = () => {
        const gridRef = useRef(null);
    
        useEffect(() => {
            if (gridRef.current) {
                while (gridRef.current.firstChild) {
                    gridRef.current.removeChild(gridRef.current.firstChild);
                }
            }
        }, []);
    
        return (
            <div ref={gridRef}>
                <Grid
                    data={[
                        ['John', 'john@example.com'],
                        ['Mike', 'mike@gmail.com']
                    ]}
                    columns={['Name', 'Email']}
                    search={true}
                    sort={true}
                />
            </div>
        )
    }
    
    export default Grid1
    

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:12:44