[英]Draft.js adding hyperlink using applyEntity doesn't seem to work
我已經研究這個問題一段時間了,我希望它不是一個錯誤。
我正在使用 Draft.js 測試文本編輯器,我只是希望我的用戶向他們的文章添加超鏈接,因此我通過修改編輯器狀態的內容為此創建了一個函數。
const addLlink = (e) => {
e.preventDefault();
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
'LINK', 'MUTABLE', {url: 'https://www.amazon.com'} // link for testing only
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const contentStateWithLink = Modifier.applyEntity(
contentStateWithEntity,
editorState.getSelection(),
entityKey
);
// tried with and without styling
const styledContentStateWithLink = Modifier.applyInlineStyle(
contentStateWithLink,
editorState.getSelection(),
'HYPERLINK'
);
const newState = EditorState.set(editorState, {
currentContent: styledContentStateWithLink
});
setEditorState(newState);
// Also tried: setEditorState(RichUtils.toggleLink(newState, newState.getSelection(), entityKey));
}
當我觸發它時,我只使用一個 Evergreen-ui 按鈕:
<Button onMouseDown={addLlink} appearance="minimal">Link</Button>
我使用 Modifier 對象實現的樣式有效,但我似乎無法獲得實際工作的鏈接。 應該注意的是,鏈接插件作為一個包,效果很好,但這僅用於檢測輸入/粘貼的 URL(未嵌入到文本中)。
對於使用 React 函數式編程的鏈接,有沒有人有實際的工作示例,或者我可能做錯了什么的建議?
事實證明,我需要添加一個裝飾器才能檢測到實體。 我將此代碼放在編輯器組件的上方/外部:
const findLinkEntities = (contentBlock, callback, contentState) => {
contentBlock.findEntityRanges(
(character) => {
const entityKey = character.getEntity();
return (
entityKey !== null &&
contentState.getEntity(entityKey).getType() === 'LINK'
);
},
callback
);
}
const Link = (props) => {
const {url} = props.contentState.getEntity(props.entityKey).getData();
return (
<a href={url} >
{props.children}
</a>
);
};
const strategyDecorator = new CompositeDecorator([
{
strategy: findLinkEntities,
component: Link,
},
]);
基本上,當您使用 EditorState 設置新內容時,它會檢測鏈接實體並將它們轉換為元素:
const newState = EditorState.set(editorState, {
currentContent: styledContentStateWithLink,
decorator: strategyDecorator
});
根據官方示例,您需要添加一個裝飾器來查找實體並應用 Link 組件
const decorator = new CompositeDecorator([
{
strategy: findLinkEntities,
component: Link,
},
]);
當您使用 linkify 插件時,您必須將裝飾器傳遞給插件編輯器
import Editor from "draft-js-plugins-editor";
import createLinkifyPlugin from "draft-js-linkify-plugin";
import "draft-js-linkify-plugin/lib/plugin.css";
...
<Editor
decorators={[decorator]}
editorState={editorState}
onChange={setEditorState}
plugins={[linkifyPlugin]}
/>
...
你可以在這里查看工作示例https://codesandbox.io/s/test-selection-decorator-draft-js-link-0lblg?file=/src/ExtendedEditor.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.