使用 draftjs 创建 React 富文本编辑器

时间:2025-01-22 14:21:49

参考网页:

  1. /building-rich-text-editors-in-react-using-draft-js-and-react-draft-wysiwyg/
  2. /questions/55417190/issue-in-showing-file-upload-for-image-in-draft-js
  3. /jpuri/draftjs-to-html#user-content-supported-conversions

首先安装若干依赖包:

npm i draft-js react-draft-wysiwyg dompurify draftjs-to-html

最终代码如下():

import React, { useState } from "react";
import { EditorState, convertToRaw } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import DOMPurify from "dompurify";
import draftToHtml from "draftjs-to-html";
import "react-draft-wysiwyg/dist/";
import "./";
const App = () => {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const [uploadedImages, setUploadedImages] = useState([]);

  const handleEditorChange = (state) => {
    setEditorState(state);
  };

  const createMarkup = (html) => {
    return {
      __html: DOMPurify.sanitize(html),
    };
  };

  const rawContentState = convertToRaw(editorState.getCurrentContent());
  const markup = draftToHtml(
    rawContentState
    // hashtagConfig,
    // directional,
    // customEntityTransform
  );

  const _uploadImageCallBack = (file) => {
    // long story short, every time we upload an image, we
    // need to save it to the state so we can get it's data
    // later when we decide what to do with it.

    // Make sure you have a uploadImages: [] as your default state
    let newImages = uploadedImages;

    const imageObject = {
      file: file,
      localSrc: URL.createObjectURL(file),
    };

    newImages.push(imageObject);

    setUploadedImages(newImages);

    // We need to return a promise with the image src
    // the img src we will use here will be what's needed
    // to preview it in the browser. This will be different than what
    // we will see in the  file we generate.
    return new Promise((resolve, reject) => {
      resolve({ data: { link: imageObject.localSrc } });
    });
  };

  return (
    <div className="App">
      {/* <header className="App-header">Rich Text Editor Example</header> */}
      <Editor
        editorState={editorState}
        onEditorStateChange={handleEditorChange}
        wrapperClassName="wrapper-class"
        editorClassName="editor-class"
        toolbarClassName="toolbar-class"
        toolbar={{
          inline: { inDropdown: true },
          list: { inDropdown: true },
          textAlign: { inDropdown: true },
          link: { inDropdown: true },
          history: { inDropdown: true },
          image: { uploadCallback: _uploadImageCallBack },
          inputAccept:
            "application/pdf,text/plain,application/,application/msword,application/-excel",
        }}
      />
      <p>------------After Editor--------------</p>
      <div
        className="preview"
        // dangerouslySetInnerHTML={createMarkup(markup)}
        dangerouslySetInnerHTML={{ __html: markup }}
      ></div>
    </div>
  );
};
export default App;

存在以下缺点:

  1. 不能一次上传多张图片。
  2. chrome dev tool console 有以下警告,不知道怎么解。
    :220 Warning: Can’t call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to directly or define a state = {}; class property with the desired state in the r component.
    先将 draftjs 卸载: npm uninstall draft-js
    然后安装旧版: 0.10.5 npm install draft-js@0.10.5 --force,后面没有出现过app crash。
  3. 没试过怎么存后端数据库。
  4. 理论上必须调用 (html) 但不知什么原因,上传的图片被过滤掉了,所以没有调用此函数。

不知道**** 博客的编辑器是怎么实现的。