4

问题

draft-js我正在尝试为使用+创建的内容创建一个编辑界面draft-js-mention-plugin。但是,editorState没有持久化,只有纯文本。提及被保存为对象数组。现在我需要使用该数据重新创建 editorState。


例子:

我有这样的纯文本:

const content = '@marcello we need to add spell check'

还有一个mentions像这样的对象的数组:

const mentions = [{
  length: 8,
  offset: 0,
  user: 'user:59441f5c37b1e209c300547d',
}]

要使用纯文本创建 editorState,我使用以下几行:

const contentState = ContentState.createFromText(content)
EditorState.createWithContent(contentState)

效果很好。纯文本设置为初始状态,但没有提及。

现在我需要一种基于mentions对象添加提及的方法。

我正在尝试阅读库代码以找出答案,但到目前为止还没有成功。

4

3 回答 3

6

和你可以"draft-js": "^0.11.6""draft-js-mention-plugin": "^3.1.5"

const stateWithEntity = editorState.getCurrentContent().createEntity(
  'mention',
  'IMMUTABLE',
  {
    mention: {id: 'foobar', name: 'foobar', link: 'https://www.facebook.com/foobar'},
  },
)
const entityKey = stateWithEntity.getLastCreatedEntityKey()
const stateWithText = Modifier.insertText(stateWithEntity, editorState.getSelection(), 'foobar', null, entityKey)
EditorState.push(editorState, stateWithText)

你可以找到这个https://github.com/draft-js-plugins/draft-js-plugins/issues/915#issuecomment-386579249https://github.com/draft-js-plugins/draft-js-插件/问题/983#issuecomment-382150332有帮助

于 2020-11-02T13:36:52.370 回答
2

我如何“破解”我的解决方案:

// Imports
import { EditorState,convertToRaw, ContentState, convertFromRaw, genKey, ContentBlock  } from 'draft-js';
// Init some kind of block with a mention
let exampleState = {
  blocks: [
        {
          key: genKey(), //Use the genKey function from draft
          text: 'Some text with mention',
          type: 'unstyled',
          inlineStyleRanges: [],
          data: {},
          depth: 0,
          entityRanges: [
            { offset: 15, length: 7, key: 0 }
          ]
        }
  ],
  entityMap: [
    "0": {
      "type": "mention",
      "mutability": "SEGMENTED",
      "data": {
        "mention": {
          "name": "<name>",
          "link": "<link>",
          "avatar": "<avatar-url>"
        }
      }
    }
  ]
};
this.state.editorState = EditorState.createWithContent(convertFromRaw(exampleState));

在这里,您可以创建一些函数来输入文本并输出 entityRange,返回提及的偏移量/长度,并用突出显示的内容替换“entityRanges”数组!

在此示例中,“提及”一词将使用提及插件使用的任何样式突出显示

边注:

您可以使用草稿中的 ContentBlock 类或创建自己的实现以使其更漂亮

于 2018-02-15T11:17:16.447 回答
1

这是我设法提出的添加提及 (#) 的解决方案(使用 entityMap,在状态结束时添加到新块)。它可以作为提及等进行检索...当然可以简化,但它对我来说可以按预期工作。

 // import {....} from 'draft-js';
 import Immutable, {List, Repeat} from 'immutable' ;

  const addMentionLast = (editorState, mentionData) => {
   
    if(!mentionData.id) return;

    // debugger;
    const contentState = editorState.getCurrentContent();
    const oldBlockMap = contentState.getBlockMap();
    const lastKey = lastNonEmptyKey(contentState);
    const charData = CharacterMetadata.create();
    
    //new state with mention
    const selection = editorState.getSelection();
    const entityKey = Entity.create('#mention', 'SEGMENTED', {"mention":{...mentionData }} );
    //add text 
    const textWithEntity = Modifier.insertText(contentState, selection , `#${mentionData.name}` , null,  entityKey); 
    const _editorState = EditorState.push(editorState,  textWithEntity ,  'insert-characters');
    
    //create new block
    const _newBlock = new ContentBlock({
      key:  genKey(),
      type: 'unstyled',
      depth: 0,
      text: mentionData.name,
      characterList: List(Repeat(charData, mentionData.name.length)),
    });

    //set the entity
    const __newBlock =  applyEntityToContentBlock(_newBlock,0, mentionData.name.length, entityKey)

    //set new block in order..
    const blocksMap =
      Immutable.OrderedMap().withMutations(map => {
        if (lastKey) {
          //after the last non empty:
          for (let [k, v] of oldBlockMap.entries()) {
            map.set(k, v);
            if (lastKey === k) {
              map.set(k, v);
              map.set(__newBlock.key, __newBlock);
            }
          }
        }
        else {
          // first line:
          map.set(__newBlock.key, __newBlock);
        }
      });
   
    return EditorState.push(
      _editorState,
          ContentState
            .createFromBlockArray(Array.from(blocksMap.values()))
            .set('selectionBefore', contentState.getSelectionBefore())
            .set('selectionAfter', contentState.getSelectionAfter())
    )

  }

  function lastNonEmptyKey (content){
    const lastNonEmpty = content.getBlockMap().reverse().skipUntil((block, _) => block.getLength()).first();
 if (lastNonEmpty) return lastNonEmpty.getKey();
}

感谢大家的分享!

于 2020-07-21T22:35:05.107 回答