1

我正在使用 HTML 编辑器开发 React 组件。

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

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

我有来自 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 进行用户输入?管理这种状态的最佳方法是什么?我已经坚持了一段时间了。

4

1 回答 1

0

这似乎工作....


    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'],
                },
            }}
        />
    </>
  );
}
于 2021-06-21T15:47:09.840 回答