如何在 React js 中管理 CKEditor 自定义插件的 onclick 事件?

2024-03-17

我想在react.js 中为 CKEditor 5 创建一个自定义插件,如下所示:

StackOverFlow 问题: CKEditor 5 通过外部 url 插入图像 https://stackoverflow.com/questions/51642683/ckeditor-5-insert-image-by-external-url

CKEditor 文档: 创建一个简单的插件 https://ckeditor.com/docs/ckeditor5/latest/framework/guides/creating-simple-plugin.html

在上面的示例中,当单击插件时,将执行以下代码并且用户输入图像 URL:

const imageUrl = prompt( 'Image URL' );

这是在init()插件类的方法。但我想做的是:

单击自定义插件时,我希望打开一个反应组件,然后用户选择一个图像,并将所选图像的 URL 传递到 CKEditor 进行插入。我读过很多文章和 Stackoverflow Q&As,但仍然不知道如何在 React 中管理插件的单击事件以打开组件并将 URL 传递给 CKEditor。

P.S:我正在使用 CKEditor 的构建版本,我正在自定义并自己构建它(例如本文 https://medium.com/@jacobtamus/ckeditor5-custom-react-editor-tutorial-a9e91aab9d16)。所以我不会将 CKEditor 集成到我的项目中,这是在 React 中使用它的另一种选择。


我找不到确切的解决方案。相反,我最终使用 CKEditor 旁边的按钮来插入图像,整个插入过程都在 React 的控制之下。

import React from "react";
import { useState } from "react";
import { CKEditor } from "@ckeditor/ckeditor5-react";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";

const MyEditor = () => {
  const [editorInstance, setEditorInstance] = useState("");
  const insertImage = () => {
    const imageUrl = prompt("Image URL"); //the process of getting the image's url in React
                                          //here, it is only a prompt but it could be any function that is managed in React
    editorInstance.model.change((writer) => {
      const imageElement = writer.createElement("image", {
        src: imageUrl,
      });
      // Inserting the image in the current selection location.
      editorInstance.model.insertContent(
        imageElement,
        editorInstance.model.document.selection
      );
    });
  };
  return (
    <div className="container">
      <button onClick={insertImage}> Insert Image from Media Library </button>
      <CKEditor
        editor={ClassicEditor}
        onReady={(editor) => {
          setEditorInstance(editor);
        }}
      />
    </div>
  );
};

export default MyEditor;

这就是我在上面的代码中所做的:

  • 我将 CKEditor 的瞬间保存在onReady event.
  • 我使用了实例(editorInstance) in inserImage method.
  • In insertImage方法 我从函数中获取图像 URL。
  • 然后我使用以下方法在编辑器中插入了所需的内容(此处为图像)editorInstance.model.change and editorInstance.model.insertContent.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 React js 中管理 CKEditor 自定义插件的 onclick 事件? 的相关文章

随机推荐