如何在react-draft-wysiwyg中渲染动态<table>标签
解决react-draft-wysiwyg渲染HTML表格内容异常的问题
问题根源
Draft.js 原生的 convertFromHTML 方法默认不支持解析<table>、<tr>、<td>等表格相关标签,会直接忽略这些标签的结构,将表格内的所有文本内容合并成普通文本块,最终导致表格内容全部挤在一行显示。
解决方案
推荐使用 draft-js-import-html 配合表格插件来实现表格的正确解析与渲染,以下是具体实现步骤:
1. 安装依赖
npm install draft-js-import-html draft-js-table-plugin react-draft-wysiwyg
2. 修改组件代码
import React, { Component } from 'react'; import { EditorState, ContentState } from 'draft-js'; import { Editor } from 'react-draft-wysiwyg'; import draftToHtml from 'draftjs-to-html'; import { stateFromHTML } from 'draft-js-import-html'; import createTablePlugin from 'draft-js-table-plugin'; import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'; import 'draft-js-table-plugin/lib/plugin.css'; // 创建表格插件 const tablePlugin = createTablePlugin(); const { InsertTableButton } = tablePlugin; export default class EditorConvertToHTML extends Component { constructor(props) { super(props); const html = ` <div> some html content here... <table style="height: 74px; width: 644px;" border="0"> <tbody> <tr> <td><strong>Customer</strong></td> <td><strong>Customer PO</strong></td> </tr> <tr> <td><span>Customer name</span></td> <td><span>po number</span></td></tr> <tr> <td><strong>Customer Complaint Number</strong></td> <td><strong>Invoice Number</strong></td> <td> </td> </tr> <tr> <td><span></span></td> <td><span>other value</span></td> <td> </td> </tr> </tbody> </table> </div> some more html content ... `; // 使用stateFromHTML解析包含表格的HTML const contentState = stateFromHTML(html); const editorState = EditorState.createWithContent(contentState); this.state = { editorState, }; } onEditorStateChange = (editorState) => { this.setState({ editorState, }); }; render() { const { editorState } = this.state; return ( <div> <Editor editorState={editorState} wrapperClassName="demo-wrapper" editorClassName="demo-editor" onEditorStateChange={this.onEditorStateChange} plugins={[tablePlugin]} // 启用表格插件 toolbarCustomButtons={[<InsertTableButton />]} // 可选:添加插入表格按钮 /> <textarea disabled value={draftToHtml(editorState.getCurrentContent().toJS())} /> </div> ); } }
关键说明
stateFromHTML来自draft-js-import-html,相比原生的convertFromHTML,它能正确识别并解析表格标签,生成对应的Draft.js内容块。draft-js-table-plugin提供了表格的渲染逻辑和样式,确保表格在编辑器中正常显示。
补充说明
如果尝试react-quill也出现类似问题,大概率是导入HTML时未配置表格相关解析规则,react-quill可通过自定义modules中的clipboard配置扩展HTML处理规则,核心思路一致。
内容的提问来源于stack exchange,提问作者Ankit Giri
相关产品推荐
相关产品推荐

