首页 > 解决方案 > 如何在 ckeditor4-react 中添加自定义插件?

问题描述

我已经按照 CKEditor 4 文档创建了一个基本插件,但它似乎没有在我的反应应用程序中注册。我添加了插件文件结构,并在节点模块中添加了 plugin.js 以及图标。如何将它传递给 ckeditor4-react 中的配置?

import logo from './logo.svg';
import './App.css';
import CKEditor from 'ckeditor4-react';

function App() {

  return (
    <div className="App">
      <header className="App-header">
      <h2>Using CKEditor 4 in React</h2>
                <CKEditor
                    config={{
                      extraPlugins: "timestamp"
                    }}
                    data="<p>Hello from CKEditor 4!</p>"
                />

在 plugin.js (node_modules/ckeditor4-react/plugins/timestamp/plugin.js

CKEDITOR.plugins.add( 'timestamp', {
    icons: 'timestamp',
    init: function( editor ) {
        editor.addCommand( 'insertTimestamp', {
            exec: function( editor ) {
                var now = new Date();
                editor.insertHtml( 'The current date and time is: <em>' + now.toString() + '</em>' );
            }
        });
        editor.ui.addButton( 'Timestamp', {
            label: 'Insert Timestamp',
            command: 'insertTimestamp',
            toolbar: 'insert'
        });
    }
});

标签: reactjsckeditor4.xckeditor4-react

解决方案


您可以通过以下方式实现加载自定义插件。

import CKEditor from "ckeditor4-react";

function App() {
  return (
    <div className="App">
      <CKEditor
        data="<p>Hello from CKEditor 4!</p>"
        config={{
          toolbar: [["Bold"], ["Timestamp"]],
          extraPlugins: "timestamp",
        }}
        onBeforeLoad={(CKEDITOR) => {
          CKEDITOR.plugins.add("timestamp", {
            init: function (editor) {
              editor.addCommand("insertTimestamp", {
                exec: function (editor) {
                  var now = new Date();
                  editor.insertHtml(
                    "The current date and time is: <em>" +
                      now.toString() +
                      "</em>"
                  );
                },
              });
              editor.ui.addButton("Timestamp", {
                label: "Insert Timestamp",
                command: "insertTimestamp",
                toolbar: "insert",
                icon: "https://cdn4.iconfinder.com/data/icons/24x24-free-pixel-icons/24/Clock.png",
              });
            },
          });
        }}
      />
    </div>
  );
}

export default App;

您还可以将本地图标(确保图标的大小为 24x24)传递给插件,例如 -

import timestampIcon from "./timestampIcon.svg';

...

   editor.ui.addButton("Timestamp", {
         label: "Insert Timestamp",
         command: "insertTimestamp",
         toolbar: "insert",
         icon: timestampIcon
   });

...

推荐阅读