如何在反应草案所见即所得上设置defaultValue

Jer*_*rin 5 javascript arrays reactjs react-draft-wysiwyg

我的数据库中有一个属性product_des,其中存储了所有内容react draft wysiwyg。我想从数据库中设置编辑器的默认值。

//State
    const [onEditorStateChange, setOnEditorStateChange] = useState<any>()
    const [content, setContent] = useState<any>()

<Editor
    editorState={onEditorStateChange}
    toolbarClassName="toolbarClassName"
    wrapperClassName="wrapperClassName"
    editorClassName="editorClassName"

    onEditorStateChange={newState => {
        setOnEditorStateChange(newState)
        setContent(draftToHtml(convertToRaw(newState.getCurrentContent())))
    }}
/>
Run Code Online (Sandbox Code Playgroud)

这是我的数据库示例:

{
_id: "6231a09c0a292231f0bbd16b",
title: "Controller",
reg_price: "499",

product_des: "<p>PS5</p>
"
}
Run Code Online (Sandbox Code Playgroud)

小智 8

为此,您需要执行以下操作:

import React, { Component } from 'react'
import { EditorState, ContentState, convertFromHTML } from 'draft-js'
import { Editor } from 'react-draft-wysiwyg'

class MyEditor extends Component {
  constructor(props) {
    super(props)
    this.state = {
      editorState: EditorState.createWithContent(
        ContentState.createFromBlockArray(
          convertFromHTML('<p>My initial content.</p>')
        )
      ),
    }
  }

  render() {
    return <Editor editorState={this.state.editorState} />
  }
}

export default MyEditor
Run Code Online (Sandbox Code Playgroud)

PS:根据 Package 或 ReactJS 版本,答案可能有所不同。