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

参考网页:

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

首先安装若干依赖包:

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

最终代码如下(App.js):

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/react-draft-wysiwyg.css";
import "./App.css";
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 index.md 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/vnd.openxmlformatsofficedocument.wordprocessingml.document,application/msword,application/vnd.ms-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 有以下警告,不知道怎么解。
    react.development.js: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 this.state 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. 理论上必须调用 DOMPurify.sanitize(html) 但不知什么原因,上传的图片被过滤掉了,所以没有调用此函数。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值