【问题标题】:Not able to display image in Editor无法在编辑器中显示图像
【发布时间】:2020-04-09 01:59:37
【问题描述】:

我正在使用 draft-js 和 react-draft-wysiwyg 包来显示我的应用程序的电子邮件编辑器。我能够显示正确的内容,但面临图像问题。

当图像是输入 HTML 的一部分时,它不会在编辑器中显示。请在下面找到我的示例代码。

import { Editor } from "react-draft-wysiwyg";

import {
  EditorState,
  ContentState,
  convertFromHTML
} from "draft-js";

const htmlContentFromServer =
            '<b>Bold text</b>, <i>Italic text</i><br/ ><br />' +
            '<a href="https://www.facebook.com">Example link</a><br /><br/ >' +
            '<img src="https://raw.githubusercontent.com/facebook/draft-js/master/examples/draft-0-10-0/convertFromHTML/image.png" height="112" width="200" />';

this.state = {
      editorState: EditorState.createWithContent(
        ContentState.createFromBlockArray(
          convertFromHTML(
            htmlContentFromServer
          )
        )
      )
    };

<Editor
              editorState={this.state.editorState}
              wrapperClassName="c-react-draft"
              editorClassName="demo-editor"
              onEditorStateChange={this.onEditorStateChange}
              spellCheck={true}
              wrapperId={this.props.wrapperId}
            />

我可以使用此解决方案 https://codepen.io/Kiwka/pen/YNYgWa 显示图像。

但上述解决方案仅在我使用“draft-js”包中的编辑器但我想使用“react-draft-wysiwyg”中的编辑器时才有效,因为我得到了丰富的工具栏选项。

当图像是来自“react-draft-wysiwyg”的编辑器中的 HTML 内容的一部分时,需要帮助来显示图像。

【问题讨论】:

  • 如果我的问题不清楚或需要任何澄清,请告诉我。如果我可以轻松实现以显示工具栏选项,我可以使用“draft-js”编辑器。
  • 使用了 CKEditor,它与图像和 hr 标签配合得很好。

标签: javascript reactjs draftjs react-draft-wysiwyg


【解决方案1】:

在传递给createWithContent之前,您需要使用下面的customContentStateConverter函数来转换内容状态。

const customContentStateConverter = (contentState) => {
    // changes block type of images to 'atomic'
    const newBlockMap = contentState.getBlockMap().map((block) => {
        const entityKey = block.getEntityAt(0);
        if (entityKey !== null) {
            const entityBlock = contentState.getEntity(entityKey);
            const entityType = entityBlock.getType();
            switch (entityType) {
                case 'IMAGE': {
                    const newBlock = block.merge({
                        type: 'atomic',
                        text: 'img',
                    });
                    return newBlock;
                }
                default:
                    return block;
            }
        }
        return block;
    });
    const newContentState = contentState.set('blockMap', newBlockMap);
    return newContentState;
}

示例代码如下;

const blocksFromHTML = convertFromHTML('<img src="some_image.png"/>');
var editorState = EditorState.createWithContent(customContentStateConverter(
    ContentState.createFromBlockArray(
        blocksFromHTML.contentBlocks,
        blocksFromHTML.entityMap
    )
))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 2015-09-20
    • 1970-01-01
    • 2021-07-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多