带有初始值的 Draft.js 编辑器

问题描述

我正在使用 HTML 编辑器处理 React 组件。

目前正在尝试使用 Draft.js (WYIWYG Draft.js) 中的 WYSIWYG 编辑器

文档似乎面向基于类的组件,但我正在尝试使用功能组件。

我有来自 API 调用的 HTML 文本并存储在如下变量中:

var values.overview = "<p>this is html text</p>"

我希望这是初始值 - 在编辑器组件中可见和可编辑。

我已经获得了显示文本的能力,但我很确定这是一种非常有缺陷的方法

const [editorState,setEditorState] = useState(EditorState.createWithContent(ContentState.createFromBlockArray(convertFromHTML(values.overview))));

和组件:

<Editor
    editorState={editorState}
    toolbarClassName="toolbarClassName"
    wrapperClassName="wrapperClassName"
    editorClassName="editorClassName"                
/>

如何根据用户输入更新状态?
我是否需要使用 Content State 来进行用户输入? 管理这种状态的最佳方法是什么? 我已经坚持了一段时间了。

解决方法

这似乎有效....


    var overview = "<u>this is my text</u>";

    const contentDataState = ContentState.createFromBlockArray(convertFromHTML(overview));
    const editorDataState = EditorState.createWithContent(contentDataState);
    
    const [editorState,setEditorState] = useState(editorDataState);
    
    const onEditorStateChange = (editorStateData) => {
        setEditorState(editorStateData);
    };

    const data = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    console.log(data);

  return (
    <>
          <Editor
            editorState={editorState}
            onEditorStateChange={onEditorStateChange}
            wrapperClassName="wrapperClassName"
            editorClassName="editorClassName"
            toolbarClassName="toolbar-class"
            toolbar={{
                options: ['inline','list','textAlign'],inline: {
                    options: ['bold','italic','underline'],},list: {
                    options: ['unordered','ordered','indent','outdent'],textAlign: {
                    options: ['left','center','right'],}}
        />
    </>
  );
}