gpt4 book ai didi

draftjs - Draft.js - 添加没有选择文本的链接

转载 作者:行者123 更新时间:2023-12-04 23:14:29 29 4
gpt4 key购买 nike

如何添加链接?我知道如何添加链接到 选择

              const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
'LINK',
'MUTABLE',
{url: urlValue}
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newEditorState = EditorState.set(editorState, { currentContent: contentStateWithEntity });
this.setState({
editorState: RichUtils.toggleLink(
newEditorState,
newEditorState.getSelection(),
entityKey
)}
我们得到选择 newEditorState.getSelection()并添加链接。
但是如何在没有选择的情况下添加链接?只需添加新 a如果未选择文本,则使用文本标记?如果我不选择任何文本,它不会添加任何内容。

最佳答案

我非常简洁的解决方案。带有很酷的注释

insertLink = (type, data, text) => {
const editorState = this.state.editorState;
const contentState = editorState.getCurrentContent();
const selection = editorState.getSelection();
const textWithSpace = text.concat(' ');
// create new content with text
const newContent = Modifier.insertText(
contentState,
selection,
textWithSpace,
);
// create new link entity
const newContentWithEntity = newContent.createEntity(
type,
'MUTABLE',
data,
false,
);
const entityKey = newContentWithEntity.getLastCreatedEntityKey();
// create new selection with the inserted text
const anchorOffset = selection.getAnchorOffset();
const newSelection = new SelectionState({
anchorKey: selection.getAnchorKey(),
anchorOffset,
focusKey: selection.getAnchorKey(),
focusOffset: anchorOffset + text.length,
});
// and aply link entity to the inserted text
const newContentWithLink = Modifier.applyEntity(
newContentWithEntity,
newSelection,
entityKey,
);
// create new state with link text
const withLinkText = EditorState.push(
editorState,
newContentWithLink,
'insert-characters',
);
// now lets add cursor right after the inserted link
const withProperCursor = EditorState.forceSelection(
withLinkText,
newContent.getSelectionAfter(),
);
// update the editor with all changes
this.setState({editorState: withProperCursor });
};

关于draftjs - Draft.js - 添加没有选择文本的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47084605/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com