react富文本编辑器react-draft-wysiwyg的使用
一、前言以及效果图
本文主要记录react中富文本编辑器react-draft-wysiwyg的使用
(npm中react-draft-wysiwyg的官方地址为https://www.npmjs.com/package/react-draft-wysiwyg)
富文本编辑器
二、使用步骤
1.下载依赖
1 2 3 4
| npm install react-draft-wysiwyg npm install draft-js npm install draftjs-to-html npm install html-to-draftjs
JSX
|
2.引入相关依赖和样式
1 2 3 4 5
| 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';
JSX
|
3.初始化
react-draft-wysiwyg一般是被当做一个子组件进行使用的。
“子组件”核心代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import React,{useEffect,useState} 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(() => { 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> <Editor editorState={editorState} toolbarClassName="toolbarClassName" wrapperClassName="wrapperClassName" editorClassName="editorClassName" onEditorStateChange={(editorContent) => setEditorState(editorContent)} onBlur={() => { // console.log() // 失去焦点时,把内容传给父组件 props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent()))); }} /> </div> ) }
JSX
|
4.在父组件中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import React, { useState, useRef, useEffect } from 'react'
import NewsEditor from "@/components/News/NewsEditor" export default function NewsAdd(props) {
const [content, setContent] = useState("") return ( <div> <NewsEditor content={content} getContent={(value) => { setContent(value); console.log("content", content); }} /> </div > ) }
JSX
|
三、验证
验证成功