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>