Draft-js在editorState currentContent中获得提名位置

时间:2017-02-28 15:25:47

标签: javascript reactjs draft-js-plugins

我正在使用draft-js-mention-plugin,而我正在寻找一种方法,可以在整个文本中返回提及位置(不使用indexOf())。

例如,我希望在这句话中得到piRstone的开头和结尾位置: Welcome to piRstone, our new colleague.

我应该在开始位置获得11,为结尾获得19

<div className="editor">
    <Editor
        editorState={this.state.editorState}
        onChange={this.onEditorChange}
        plugins={plugins}
        // placeholder={this.state.placeholder}
        ref={(element) => { this.editor = element; }}
    />
    <MentionSuggestions
        onSearchChange={this.onSearchChange}
        suggestions={this.state.suggestions}
        onAddMention={this.onAddMention}
    />
</div>

这是我的onAddMention()方法:

onAddMention(object) {
    console.log(object);
}

也许有一种更简单的方法可以使用,但提到的插件文档有点弱。

1 个答案:

答案 0 :(得分:0)

您将在块的entityRanges对象中获得特定提及的偏移量和长度,偏移量将是初始索引,偏移量+提及的长度将是最后一个索引

[
  {
    "key": "4p8mh",
    "text": "Nice to meet you #name#",
    "type": "unstyled",
    "depth": 0,
    "inlineStyleRanges": [],
    "entityRanges": [
      {
        "offset": 20,
        "length": 6,
        "key": 0
      }
    ],
    "data": {}
  }
]

通过迭代此对象,您将获得偏移量和长度

Object.keys(content.blocks).map(i => {
         const {entityRanges, text} = content.blocks[i];
         entityRanges.map((range, idx) => {
              console.log(range.offset)
              console.log(range.length)
         });
    });