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

React环境下CKEditor4光标位置动态插入文本实现方案咨询

React中CKEditor4插入内容到光标位置的实现方案

要实现点击按钮将内容插入到CKEditor4的光标位置,核心是拿到编辑器实例并调用其内置API,具体实现如下:

  1. 保存CKEditor实例
    通过组件的onInstanceReady事件获取编辑器实例,存入React状态,方便后续调用API。

  2. 调用插入API
    使用CKEditor4的insertText()(插入纯文本)或insertHtml()(插入富文本)方法,这两个方法会自动将内容插入到当前光标所在位置。

完整代码示例:

import { CKEditor } from "ckeditor4-react";
import { useState } from "react";

const TextEditor = () => {
  // 保存CKEditor实例
  const [editorInstance, setEditorInstance] = useState<CKEditor | null>(null);

  function handleClick(fruit: string) {
    if (editorInstance) {
      // 插入纯文本,如需插入富文本可改用insertHtml()
      editorInstance.insertText(fruit);
      // 可选:插入后让编辑器重新获得焦点
      editorInstance.focus();
    }
  }

  return (
    <>
      <div>
        {["Apple", "Banana", "Grape", "Pineapple"].map((item) => (
          <button key={item} onClick={() => handleClick(item)}>
            {item}
          </button>
        ))}
      </div>

      <CKEditor
        initData="<p>This is an example CKEditor 4 WYSIWYG editor instance.</p>"
        onInstanceReady={(evt) => {
          // 保存编辑器实例
          setEditorInstance(evt.editor);
        }}
      />
    </>
  );
};

export default TextEditor;

关键说明

  • onInstanceReady事件在编辑器完全初始化完成后触发,此时可以安全获取实例。
  • 如果需要插入带格式的内容(比如<strong>Apple</strong>),将insertText()替换为insertHtml()即可。
  • 调用focus()方法可以让编辑器在插入内容后重新获得焦点,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:15:43