Draftjs Draft.js。我以后如何更新block-atomic:image-src,例如文章save?
在draft.js中更新editorState中的图像块时遇到问题。 我想在保存按钮上更改原子:image src。 例如,src现在是blob: 但是我想更新到src,例如/uploads from my server/test.pngDraftjs Draft.js。我以后如何更新block-atomic:image-src,例如文章save?,draftjs,draft-js-plugins,Draftjs,Draft Js Plugins,在draft.js中更新editorState中的图像块时遇到问题。 我想在保存按钮上更改原子:image src。 例如,src现在是blob: 但是我想更新到src,例如/uploads from my server/test.png onSave(e) { e.preventDefault(); const { editorState } = this.state; const contentState = editorState.getCurrentContent(); edi
onSave(e) {
e.preventDefault();
const { editorState } = this.state;
const contentState = editorState.getCurrentContent();
editorState.getCurrentContent().getBlockMap().map((block) => {
const type = block.getType();
if (type === 'atomic:image') {
const rangeToReplace = new SelectionState({
anchorKey: block.getKey(),
focusKey: block.getKey(),
});
Modifier.replaceText(contentState, rangeToReplace, '/uploads-from-my-server/test.png');
const newContentState = editorState.getCurrentContent();
this.setState({ editorState: newContentState });
}
return true;
});
我知道我可以使用block.getData().get('src')访问src字符串,但我无法设置
感谢您的出色编辑器我遇到了一个类似的问题,我最终使用
convertToRaw
将内容状态转换为原始数组,然后手动更新,并使用convertFromRaw
设置新状态:
import {EditorState, ContentState, convertToRaw, convertFromRaw /*, ...*/} from 'draft-js';
// ...
onSave(e) {
e.preventDefault();
const { editorState } = this.state;
const contentState = editorState.getCurrentContent();
let rawContent = convertToRaw(contentState);
for(let i = 0; i < rawContent.blocks.length; i++) {
let b = rawContent.blocks[i];
if(b['type'] !== "unstyled" && b.entityRanges.length === 1) {
const entityKey = b['entityRanges'][0]['key'];
const entityMap = rawContent['entityMap'][entityKey];
if(entityMap["type"] === "image") {
rawContent['entityMap'][entityKey]['data']['src'] = '/uploads-from-my-server/test.png';
}
}
}
const newContentState = convertFromRaw(rawContent);
const newEditorState = EditorState.push(this.state.editorState, newContentState, 'update-contentState');
this.setState({editorState: newEditorState});
}
从“草稿js”导入{EditorState、ContentState、convertToRaw、convertFromRaw/*,…*/};
// ...
昂萨维(e){
e、 预防默认值();
const{editorState}=this.state;
const contentState=editorState.getCurrentContent();
设rawContent=convertToRaw(contentState);
for(设i=0;i
注意:这不是一个完全有效的示例,它只是一个起点。希望有帮助:)谢谢,我会试试看