这是我设法为添加提及 (#)(使用 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();
}
感谢大家的分享!