1

我正在使用 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);
}

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

4

1 回答 1

0

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

[
  {
    "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)
         });
    });
于 2020-06-12T05:23:03.040 回答