react-draft-wysiwyg富文本编辑器

在React项目中使用

yarn add react-draft-wysiwyg draft-js
or
npm i react-draft-wysiwyg draft-js

推荐在项目中单独创建一个富文本编辑器组件

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


<Editor
      editorState={editorState}
      toolbarClassName="aaaaa"
      wrapperClassName="bbbbb"
      editorClassName="ccccc"
      onEditorStateChange={(editorState)=>setEditorState(editorState)}

      onBlur={()=>{
	   console.log(draftToHtml(convertToRaw(editorState.getCurrentContent())))
	   props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
	}}
 />

转化成HTML的方式,就需要借助draftjs-to-html,所以我们需要先安装它

yarn add draftjs-to-html
or
npm i draftjs-to-html

整体代码

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

export default function NewsEditor(props) {
    const [editorState, setEditorState] = useState("")
    // useEffect(()=>{
    //     // console.log(props.content)
    //     // html-===> draft, 
    //     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="aaaaa"
                wrapperClassName="bbbbb"
                editorClassName="ccccc"
                onEditorStateChange={(editorState)=>setEditorState(editorState)}

                onBlur={()=>{
                    console.log(draftToHtml(convertToRaw(editorState.getCurrentContent())))

                    props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
                }}
            />
        </div>
    )
}

页面效果

react-draft-wysiwyg富文本编辑器_第1张图片
有一个小问题,在频繁输入(数字或者字母等)的时候会报错
react-draft-wysiwyg富文本编辑器_第2张图片
GitHub上有相应的问题提出,但是好像还没具体的解决方案:https://github.com/facebookarchive/draft-js/issues/1943

你可能感兴趣的:(react.js,前端,前端框架)