Draft.js。我怎样才能更新block atomic:image src,例如文章保存?

时间:2017-07-19 09:04:59

标签: draftjs draft-js-plugins

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

<a href="#" id="ddnmenu">Bentornato {$mybb->user['username']}! <i class="fa fa-caret-down"></i></a>
<div id="ddnmenu_popup" class="popup_menu" style="display: none;">
  <div class="popup_item_container">
    <a href="{$mybb->settings['bburl']}/usercp.php" class="popup_item">User Panel<i class="fa fa-user menuadj"></i></a>
  </div>
  <div class="popup_item_container">
    <a href="{$mybb->settings['bburl']}/usercp.php?action=profile" class="popup_item">Edit Profile<i class="fa fa-pencil menuadj"></i></a>
  </div>
  <div class="popup_item_container">
    <a href="{$mybb->settings['bburl']}/usercp.php?action=options" class="popup_item">Edit Options<i class="fa fa-cogs menuadj"></i></a>
  </div>
  <div class="popup_item_container">
    <a href="{$mybb->settings['bburl']}/usercp.php?action=avatar" class="popup_item">Edit Avatar<i class="fa fa-picture-o menuadj"></i></a>
  </div>
  <div class="popup_item_container">
    <a href="{$mybb->settings['bburl']}/usercp.php?action=editsig" class="popup_item" style="padding-bottom: 4px;">Edit Signature<i class="fa fa-paint-brush menuadj"></i></a>
  </div>
  <div class="popup_item_container">
    <a href="{$mybb->settings['bburl']}/member.php?action=logout&amp;logoutkey={$mybb->user['logoutkey']}" class="popup_item">{$lang->welcome_logout}!<i class="fa fa-power-off menuadj"></i>
                        </a>
  </div>
</div>

我知道我可以使用block.getData()访问src字符串.get(&#39; src&#39;)但是我无法设置

感谢您的精彩编辑

1 个答案:

答案 0 :(得分: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});
}

注意:这不是一个完全有效的例子,它只是一个起点。希望它有所帮助:)