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

React Native中react-native-render-html渲染HTML表格异常的解决建议

解决react-native-render-html无法正常显示表格的问题

问题场景

使用react-native-render-html渲染CKEditor生成的HTML表格时,表格内容无法正常显示,代码示例如下:

import RenderHtml from 'react-native-render-html';
import { WebView } from 'react-native-webview';

const html = `
        <html>
        <head></head>
            <body>
            <style>
                table, th, td {
                    border:1px solid black;
                }
            </style>

            <table style="width:100%">
                <tr>
                <td>Emil</td>
                <td>Tobias</td>
                <td>Linus</td>
                </tr>
                <tr>
                <td>16</td>
                <td>14</td>
                <td>10</td>
                </tr>
            </table>
            </body>
        </html>
    `;

    const webViewProps = {
        originWhitelist: "*"
    };

    return (
        <View style={{ flex: 1 }}>
            <RenderHtml
                source={{ html }}
                WebView={WebView}
                defaultWebViewProps={webViewProps}
            />
        </View>
    );

解决方案

1. 使用官方表格插件

react-native-render-html默认不支持表格渲染,需安装并启用专门的表格插件:

  • 安装依赖:
    npm install @native-html/table-plugin --save
    # 或
    yarn add @native-html/table-plugin
    
  • 修改代码配置插件:
    import RenderHtml from 'react-native-render-html';
    import { WebView } from 'react-native-webview';
    import { tablePlugin } from '@native-html/table-plugin';
    import { MediaQuery } from 'react-native';
    
    const html = `...`; // 你的CKEditor生成的HTML
    
    // 注册表格插件
    const plugins = [tablePlugin];
    
    return (
      <View style={{ flex: 1 }}>
        <RenderHtml
          source={{ html }}
          WebView={WebView}
          plugins={plugins}
          // 必须指定contentWidth以确保表格正确布局
          contentWidth={MediaQuery.matchMedia('(max-width: 768px)').width}
        />
      </View>
    );
    

2. 直接使用WebView渲染

如果插件方式无法满足需求,直接用WebView完整渲染HTML,避免react-native-render-html的解析限制:

import { WebView } from 'react-native-webview';
import { View } from 'react-native';

const html = `...`; // 你的CKEditor生成的HTML

return (
  <View style={{ flex: 1 }}>
    <WebView
      originWhitelist={["*"]}
      source={{ html }}
      style={{ flex: 1 }}
    />
  </View>
);

3. 优化HTML样式适配RN环境

调整CKEditor生成的HTML样式,确保表格样式在RN环境中生效:

<html>
<head>
  <style>
    table {
      display: table !important;
      width: 100%;
      border-collapse: collapse;
    }
    th, td {
      border: 1px solid black;
      padding: 8px;
      text-align: left;
    }
  </style>
</head>
<body>
  <!-- 你的表格内容 -->
</body>
</html>

添加display: table !important强制表格使用标准布局,同时补充内边距和对齐样式提升可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:18:29