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

React 18适配求助:将DataTables中ReactDOM.render改为createRoot

React 18 适配 DataTables 单元格渲染代码方案

直接将原代码中的ReactDOM.render替换为createRoot即可,具体修改步骤如下:

首先确保从react-dom/client导入createRoot:

import { createRoot } from 'react-dom/client';

然后修改DataTables的列配置代码:

{
  title: "Details",
  targets: 6,
  data: null,
  createdCell: (td, cellData, rowData, row, col) => {
    // 创建根节点并渲染按钮组件
    const root = createRoot(td);
    root.render(<button className='btn btn-primary' onClick={() => handleClick(row)}>Click</button>);
  },
}

额外注意事项

如果DataTables存在单元格复用场景(比如分页、排序操作后),建议在渲染前先清理已有的React根节点,避免重复渲染引发内存泄漏:

createdCell: (td, cellData, rowData, row, col) => {
  // 先卸载已存在的根节点
  const existingRoot = createRoot(td);
  existingRoot.unmount();
  // 重新渲染新内容
  const newRoot = createRoot(td);
  newRoot.render(<button className='btn btn-primary' onClick={() => handleClick(row)}>Click</button>);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:56:01