React中CKEditor 5实现HTML格式内容插入与提取保存的方法
React中CKEditor 5插入/提取HTML内容实现方案
核心实现逻辑
- 首先在
onReady回调中把编辑器实例挂载到组件属性上,后续所有操作都基于该实例调用官方API - 提取HTML内容必须调用实例的
getData()方法,该方法返回的是标准HTML字符串,可直接存入数据库 - 插入HTML分为全量替换和光标位置插入两种场景,按需调用对应API即可
完整修改后代码
import React, { Component } from "react"; import { CKEditor } from "@ckeditor/ckeditor5-react"; import ClassicEditor from "@ckeditor/ckeditor5-build-classic"; import ListAll from "./components/ListAll"; class App extends Component { // 存储编辑器实例 editorInstance = null; state = { // 示例:要插入的HTML内容,可根据实际需求修改 toInsertHtml: "<p style='color: red;'>这是动态插入的HTML片段</p>", // 存储从编辑器提取的内容 savedHtml: "" }; // 插入HTML到编辑器 insertHtmlHandler = () => { // 场景1:直接覆盖整个编辑器的内容 this.editorInstance.setData(this.state.toInsertHtml); // 场景2:在当前光标位置插入内容,不覆盖原有内容,注释掉上面一行启用下面代码即可 /* this.editorInstance.model.change(writer => { const viewFragment = this.editorInstance.data.processor.toView(this.state.toInsertHtml); const modelFragment = this.editorInstance.data.toModel(viewFragment); this.editorInstance.model.insertContent(modelFragment); }); */ }; // 提取编辑器内容 saveContentHandler = () => { // getData()返回标准HTML字符串 const content = this.editorInstance.getData(); this.setState({ savedHtml: content }, () => { // 此处可直接调用后端接口将content存入数据库 console.log("编辑器标准HTML内容:", content); }); }; render() { return ( <div className="App"> <Toolbar> <ListAll /> <button onClick={this.insertHtmlHandler}>插入预设HTML</button> <button onClick={this.saveContentHandler}>保存编辑器内容</button> </Toolbar> <h2>Using CKEditor 5 build in React</h2> <CKEditor editor={ClassicEditor} id="ckeditor" data="<p>Hello from CKEditor 5!</p>" onReady={(editor) => { // 保存编辑器实例 this.editorInstance = editor; }} /> </div> ); } } export default App;
常见问题说明
你之前拿到非标准HTML格式,是因为错误读取了编辑器内部的Model层数据,该数据是CKEditor内部用来维护编辑状态的自定义结构,只要调用getData()接口就能拿到符合规范的HTML内容。
内容的提问来源于stack exchange,提问作者jokr1
相关产品推荐
相关产品推荐

