首页 文章

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

提问于
浏览
0

The problem

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


Example:

我有一个这样的纯文本:

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 对象添加提及的方法 .

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

1 回答

  • 0

    我如何“入侵”我的解决方案:

    // 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类或创建自己的实现来使其更漂亮

相关问题