天天看點

【react插件-富文本框react-draft-wysiwyg】1. 安裝2. 富文本框元件3. 引用富文本元件

1. 安裝

一個一個依次安裝,一起裝可能版本沖突,頁面會報錯加載不出來。

react-draft-wysiwyg
draft-js
draftjs-to-html
html-to-draftjs
           

2. 富文本框元件

import React, { useState, useEffect } from "react";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";

export default function NewsEditor(props) {
  const [editorState, setEditorState] = useState("");

  useEffect(() => {
    // 回顯内容,将父元件傳來的html轉為富文本可識别的内容對象
    const html = props.content;
    if (html === undefined) return;
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks
      );
      const editorState = EditorState.createWithContent(contentState);
      setEditorState(editorState);
    }
  }, [props.content]);

  return (
    <div>
      {/* editorState-富文本框可識别的内容對象 */}
      <Editor
        editorState={editorState}
        toolbarClassName="toolbarClassName"
        wrapperClassName="wrapperClassName"
        editorClassName="editorClassName"
        onEditorStateChange={(editorState) => setEditorState(editorState)}
        onBlur={() => {
          // 将editorState富文本内容對象轉為html
          props.getContent(
            draftToHtml(convertToRaw(editorState.getCurrentContent()))
          );
        }}
      />
    </div>
  );
}
           

3. 引用富文本元件

import NewsEditor from "../../components/news-manage/NewsEditor";

const [content, setContent] = useState("");
<NewsEditor
  getContent={(value) => {
    setContent(value);
  }}
></NewsEditor>

<NewsEditor
  getContent={(value) => {
    setContent(value);
  }}
 content={content}
></NewsEditor>
           

繼續閱讀