2

我使用 react-draft-wysiwyg 编辑器,它的状态应该由 Formik 控制。这个想法是 Formik 的值是一个字符串,因此 Editor 状态使用 stateToHTML 转换为 HTML 并设置为值,当从 Formik 接收时,它从 HTML 转换为 EditorState。由于能够使用 Formik 方法重置表单,因此来回传递且不受 Editor 本身控制的值是必不可少的。此外,该值需要从表单作为字符串发送,后端不应该知道前端使用了哪种编辑器。

问题是,尽管带有 html 的字符串在 Formik 之间传递得很好,但更新数据却出错了。更新字符串后,光标返回到编辑器窗口的最开头(输入?)并将新键入的字符串添加到字符串前面。看起来我是从右到左打字的。但是,退格键和删除键按预期工作。

Formik 像这里一样使用它

<Field name='wysiwyg' label='Wysiwyg' component={Editor} />

这是编辑器的设置方式

const setEditorState = (html) => {
  const blocksFromHTML = convertFromHTML(html || '')
  if (blocksFromHTML.contentBlocks !== null) {
    const state = ContentState.createFromBlockArray(
      blocksFromHTML.contentBlocks,
      blocksFromHTML.entityMap
    )
    return EditorState.createWithContent(state)
  }
  return EditorState.createEmpty()
}

class XXX extends react.Component {
onEditorStateChange = (editorState) => {
    const contentState = editorState.getCurrentContent()
    this.props.form.setFieldValue(this.props.field.name, stateToHTML(contentState)) //stateToHTML imported from draft-js-export-html 
  }


render () {
   return (
      <Editor
        editorState={setEditorState(this.props.field.value)}
        onEditorStateChange={this.onEditorStateChange}
        ...
      />
    )
  }
}
4

1 回答 1

3

以防有人仍在寻找将 DraftJS 与 Formik 集成的解决方案。我发现这个非常有用的代码和框项目可以做到这一点

于 2019-08-05T16:15:08.633 回答