如何使用draft-js-mention-plugin以编程方式添加提及?

时间:2017-11-15 20:45:49

标签: reactjs draftjs draft-js-plugins

问题

我正在尝试为使用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对象添加提及的方法。

我正在尝试阅读库代码来解决它,但到目前为止没有成功。

3 个答案:

答案 0 :(得分:2)

使用"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-plugins/issues/983#issuecomment-382150332有用

答案 1 :(得分:1)

我是如何"黑客攻击"我的解决方案:

// 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: []
};
this.state.editorState = EditorState.createWithContent(convertFromRaw(exampleState));

在这里你可以创建一些函数来输入你的文本并输出一个entityRange返回提及的偏移/长度并替换" entityRanges"数组与突出显示的东西!

在这个例子中,"提及"将使用提及插件的任何样式突出显示

旁注:

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

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

感谢大家的分享!