【问题标题】:TypeError: editorState.getCurrentContent is not a function while using Draft.js EditorTypeError:使用 Draft.js 编辑器时 editorState.getCurrentContent 不是函数
【发布时间】:2021-10-10 13:01:57
【问题描述】:

我正在尝试添加 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;

【问题讨论】:

  • 您找到原因了吗?您设法解决了吗?

标签: javascript reactjs draftjs react-draft-wysiwyg


【解决方案1】:

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

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

或者useEffecteditorState

useEffect(()=>{},[editorState])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2021-09-06
    • 2017-06-21
    相关资源
    最近更新 更多