0

我正在使用 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 内容的一部分时,需要帮助来显示图像。

4

1 回答 1

2

您需要使用以下customContentStateConverter函数在传递到createWithContent.

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
    )
))
于 2020-09-05T15:21:26.563 回答