如何在Draft.js中插入/上传图像(更新实体和块)?
我正在尝试将图像插入Draft.js编辑器。
根据我的理解,我需要更新实体,mergeData
并通过阻止mergeBlockData
。(我不确定)
现在,我试图mergeBlockData
用来插入一个块。
mergeBlockData(
contentState: ContentState,
selectionState: SelectionState,
blockData: Map<any, any>
): ContentState
请阅读代码中的注释。
import { Map } from 'immutable';const selection = this.state.editorState.getSelection();
const contentState = this.state.editorState.getCurrentContent();
console.log(convertToRaw(contentState)); // for example, I have 3 blocks
const blockData = Map({ ov72: { // here how to generate a random valid key?
"key": "ov72",
"text": " ",
"type": "atomic",
"depth": 0,
"inlineStyleRanges": [],
"entityRanges": [{
"offset": 0,
"length": 1,
"key": 1
}],
"data": {}
}});
const newContentState = Modifier.mergeBlockData(contentState, selection, blockData);
console.log(convertToRaw(newContentState)); // here is wrong, still 3 blocks. Also original blocks have no change
const newEditorState = EditorState.push(this.state.editorState, newContentState);
回答:
花了一些时间弄清楚如何插入图像。
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图像插件。
现场演示: [codesandbox](https://codesandbox.io/s/50pp3xlv24)
该演示将插入一个Twitter徽标图像。
如果要从本地文件插入图像,则可以尝试使用FileReader
API来获取该base64。
对于如何获取base64,很简单,请检查
现场演示: [jsbin](http://jsbin.com/xupisiraya/2/edit?js,console,output)
现在将它们放在一起,您可以从本地文件上传图像!
以上是 如何在Draft.js中插入/上传图像(更新实体和块)? 的全部内容, 来源链接: utcz.com/qa/411597.html