0

我正在尝试添加 react-draft-wysiwyg 编辑器。我正在尝试获取编辑器的当前内容,但它显示错误,因为 getCurrentContent() 不是函数。有人可以帮忙吗?

import React, { useState } from 'react';

import { Editor } from "react-draft-wysiwyg";
import { EditorState } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { convertToHTML } from 'draft-convert';
import DOMPurify from 'dompurify';


const NoteEditor = () => {

    const [editorState, setEditorState] = useState(
        () => EditorState.createEmpty(),
    );
    const [convertedContent, setConvertedContent] = useState("");

    const handleEditorChange = (state) => {
        setEditorState(state);
        convertContentToHTML();
      }
    const convertContentToHTML = () => {
        let currentContentAsHTML = convertToHTML(editorState.getCurrentContent());
        setConvertedContent(currentContentAsHTML);
    }
    const createMarkup = (html) => {
        return  {
          __html: DOMPurify.sanitize(html)
        }
      }
      
    return(
        <div className="note-editor">
            <Editor 
                defaultEditorState={editorState}
                onChange={handleEditorChange}
                wrapperClassName="wrapper-class"
                editorClassName="editor-class"
                toolbarClassName="toolbar-class"
            />
            <div className="preview" dangerouslySetInnerHTML={createMarkup(convertedContent)}></div>
        </div>
    )
};

export default NoteEditor;
4

1 回答 1

1

你可以像这样使用,有时 useState 需要时间作为它的异步,

const handleEditorChange = (state) => {
    setEditorState(state);
    convertContentToHTML(state);
  }
const convertContentToHTML = (editorState) => {
    let currentContentAsHTML = convertToHTML(editorState.getCurrentContent());
    setConvertedContent(currentContentAsHTML);
}

useEffecteditorState,

useEffect(()=>{},[editorState])
于 2021-08-17T04:47:01.007 回答