如何在React项目中开启CKEditor5的全部HTML特性?
解决CKEditor5 React应用中GeneralHtmlSupport插件的配置问题
GeneralHtmlSupport的配置逻辑在React环境和原生JS环境完全一致,你可以通过以下两种方式完成配置,实现保留自定义HTML标签、属性和样式的需求:
方式一:在自定义构建的全局默认配置中设置
直接修改src/ckeditor.ts里的defaultConfig,添加htmlSupport字段定义需要放行的内容:
public static override defaultConfig = { toolbar: { items: [ 'sourceEditing', '|', 'heading', '|', 'style', '|', 'bold', 'italic', 'underline', '|', 'bulletedList', 'numberedList', '|', 'outdent', 'indent', 'alignment', '|', 'blockQuote', 'imageUpload', 'link', 'insertTable', 'mediaEmbed', '|', 'undo', 'redo' ] }, language: 'en', image: { toolbar: [ 'imageTextAlternative', 'toggleImageCaption', 'imageStyle:inline', 'imageStyle:block', 'imageStyle:side' ] }, table: { contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells' ] }, // 新增GeneralHtmlSupport配置 htmlSupport: { allow: [ // 保留div的align属性 { name: 'div', attributes: { 'align': true } }, // 保留table的border/cellspacing/cellpadding属性及指定样式 { name: 'table', attributes: { 'border': true, 'cellspacing': true, 'cellpadding': true, 'style': true }, styles: { 'border-collapse': true, 'border': true } } ] } };
方式二:在React组件的CKEditor实例中单独配置
如果不想修改全局默认配置,可直接在Editor.jsx的CKEditor组件中传入config属性:
import "ckeditor5-custom-build"; import { ClassicEditor } from '@ckeditor/ckeditor5-editor-classic'; export default function Editor({ template, setHtml }) { return ( <> ... <div className="editor"> <CKEditor editor={ClassicEditor} data={template} // 单独配置当前编辑器实例的HTML支持规则 config={{ htmlSupport: { allow: [ { name: 'div', attributes: { 'align': true } }, { name: 'table', attributes: { 'border': true, 'cellspacing': true, 'cellpadding': true, 'style': true }, styles: { 'border-collapse': true, 'border': true } } ] } }} onReady={(editor) => { console.log("Editor is ready: ", editor) }} onChange={(event, editor) => { const data = editor.getData(); setHtml(data); }} /> </div> </> ); }
配置说明
allow数组中的每个对象对应一个需要放行的HTML标签attributes: true表示允许该标签的对应属性,也可指定具体有效值(如'align': ['center', 'left', 'right'])styles字段用于放行特定内联样式,确保原有样式不会被CKEditor过滤- 若需保留更多标签或属性,直接在
allow数组中添加对应配置项即可
内容的提问来源于stack exchange,提问作者apun23
相关产品推荐
相关产品推荐

