【问题标题】:How can I render html on Draft editor instance?如何在草稿编辑器实例上呈现 html?
【发布时间】:2018-06-16 19:30:57
【问题描述】:

我有一个用例,我必须将 HTML 模板渲染到编辑器上。我也在探索 Draftjs。我已经完成了基本设置,并为简单的文本渲染了 Draftjs 编辑器。

但是如果我将一个 HTML 字符串传递给同一个编辑器组件,我会遇到异常。

DraftEditorContents-core.react.js:80 Uncaught TypeError: nextEditorState.getDirectionMap is not a function
    at DraftEditorContents.shouldComponentUpdate (DraftEditorContents-core.react.js:80)
    at checkShouldComponentUpdate (react-dom.development.js:11345)
    at updateClassInstance (react-dom.development.js:11754)
    at updateClassComponent (react-dom.development.js:13153)
    at beginWork (react-dom.development.js:13824)
    at performUnitOfWork (react-dom.development.js:15863)
    at workLoop (react-dom.development.js:15902)
    at HTMLUnknownElement.callCallback (react-dom.development.js:100)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:138)
    at invokeGuardedCallback (react-dom.development.js:187)

知道我需要做什么才能让这个在草稿上工作吗?如果 draftjs 不适合这个,那么你建议任何其他库作为替代方案?

【问题讨论】:

    标签: reactjs wysiwyg rich-text-editor draftjs draft-js-plugins


    【解决方案1】:

    要将 HTML 字符串传递给编辑器,您可以使用 Draftjs 编辑器提供的 convertFromHTML 函数:

    componentWillMount() {
        const compositeDecorator = new CompositeDecorator([
          {
            strategy: this.handleStrategy,
            component: HandleSpan,
            readOnly: true,
          },
        ]);
        const { value } = this.props;
        if (value) {
          const blocksFromHTML = convertFromHTML(value.replace(/(?:\r\n|\r|\n)/g, '<br /><br />'));
          const state = ContentState.createFromBlockArray(
            blocksFromHTML.contentBlocks,
            blocksFromHTML.entityMap,
          );
          this.state = {
            editorState: EditorState.createWithContent(
              state,
              compositeDecorator,
            ),
          };
        } else {
          this.state = {
            editorState: EditorState.createEmpty(),
          };
        }
      }
    

    然后你可以在渲染函数中使用 this.state.editorState 作为道具:

    <Editor
        editorState={this.state.editorState}
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多