【发布时间】:2019-06-25 23:56:40
【问题描述】:
我正在使用 Draft.js 开发一个富文本编辑器(太棒了!)。以下代码允许用户编辑链接,在逻辑上工作正常,但我对用户体验不满意。
如果用户选择链接的一部分并运行此代码,则此代码将该链接分成多个链接,这不是用户想要的。
例如,如果一个阶段“买这本书”与 URL-A 链接,并且用户选择“买这个”,并将其更改为 URL-B,则该部分将与 URL-B 链接,但“ book”仍然与 URL-A 链接。
理想情况下,当用户选择链接文本的一部分时,我想自动将选择扩展到整个链接,然后执行此代码。
但是,我不知道该怎么做(将选择扩展到整个链接)。
editLink = () => {
const { editorState } = this.state;
const selection = editorState.getSelection();
if (selection.isCollapsed()) {
return;
}
let url = ''; // default
const content = editorState.getCurrentContent();
const startKey = selection.getStartKey();
const startOffset = selection.getStartOffset();
const blockWithLinkAtBeginning = content.getBlockForKey(startKey);
const linkKey = blockWithLinkAtBeginning.getEntityAt(startOffset);
if (linkKey) {
const linkInstance = content.getEntity(linkKey);
url = linkInstance.getData().url;
}
let link = window.prompt("Paste the link", url);
if (!link) {
console.log("removing link");
const newEditorState = RichUtils.toggleLink(editorState, selection, null);
this.setState({ editorState: newEditorState });
return;
}
console.log("adding a link", link);
const contentWithEntity = content.createEntity('LINK', 'MUTABLE', { url: link });
const entityKey = contentWithEntity.getLastCreatedEntityKey();
const newEditorState = EditorState.set(editorState, { currentContent: contentWithEntity });
const yetNewEditorState = RichUtils.toggleLink(newEditorState, newEditorState.getSelection(), entityKey);
this.setState({ editorState: yetNewEditorState} );
}
非常感谢任何帮助或建议。
【问题讨论】: