2

我无法在 draft.js 的 editorState 中更新我的图像块。我想在按钮保存时更改 atomic:image src。所以 src 现在是 blob:http://localhost:3000/7661d307-871b-4039-b7dd-6efc2701b623 但我想更新到 src 例如 /uploads-from-my-server/test.png

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 字符串,但我无法设置

感谢您的出色编辑

4

1 回答 1

0

我正在努力解决类似的问题,我最终将内容状态转换为原始数组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});
}

注意:这不是一个完整的示例,它只是一个起点。希望能帮助到你 :)

于 2017-07-20T17:10:19.080 回答