无法在编辑器中显示图像

时间:2019-12-16 15:16:15

标签: javascript reactjs draftjs react-draft-wysiwyg

我正在使用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'中的Editor时,上述解决方案才有效,

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

2 个答案:

答案 0 :(得分:0)

使用CKEditor,它与图像和hr标签一起使用效果很好。

答案 1 :(得分:0)

在传递给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
    )
))