首页 文章

在draft-js编辑器中上传和渲染图像

提问于
浏览
1

我正在尝试创建一个简单的编辑器来编写故事情节 . 现在我可以在编辑器中显示html标记,粗体文本以粗体显示等等 . 我也可以将html格式的数据发送到服务器但是我无法在编辑器中显示图像而且也无法上传图像在编辑 . 我已经创建了它的代码框 . 链接在这里

https://codesandbox.io/s/5w4rp50qkp

代码行有点大 . 这就是我在codesandbox中发布代码的原因,你可以在其中看到演示 .

谁能帮助我做到这一点?

1 回答

  • 1

    我最初发表了我的回答here

    为方便起见,我将其复制到下面:


    在检查Draft.js源代码之后花了一段时间来弄清楚如何插入图像 .

    insertImage = (editorState, base64) => {
        const contentState = editorState.getCurrentContent();
        const contentStateWithEntity = contentState.createEntity(
          'image',
          'IMMUTABLE',
          { src: base64 },
        );
        const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
        const newEditorState = EditorState.set(
          editorState,
          { currentContent: contentStateWithEntity },
        );
        return AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' ');
      };
    

    然后你可以使用

    const base64 = 'aValidBase64String';
    const newEditorState = this.insertImage(this.state.editorState, base64);
    this.setState({ editorState: newEditorState });
    

    对于渲染图像,您可以使用Draft.js image plugin .

    现场演示:codesandbox

    该演示插入了Twitter徽标图像 .


    如果要从本地文件插入图像,可以尝试使用 FileReader API来获取该base64 .

    有关如何获取base64,很简单,请检查

    现场演示:jsbin

    现在继续将它们放在一起,您可以从本地文件上传图像!

相关问题