創建裝飾鏈路實體我使用Facebook的Draft.js,我需要的時候在文本中檢測到有效的URL創建一個鏈接實體。如何在Facebook上Draft.js
目前,我正在使用一個裝飾器來實現檢測文本中是否存在鏈接的策略,比如draft-js-linkify-plugin,但我有一些麻煩將該文本修改爲不可變的LINK實體。
事實上,我裝點與編輯的道具,但我不能修改編輯器的狀態,因此,將這一新的鏈路實體。
的裝飾:
const decorator = new CompositeDecorator([{
strategy: findLinks,
component: decorateComponentWithProps(Link, {
getEditorState: this.getEditorState.bind(this),
setEditorState: this.onChange.bind(this)
}),
}]);
策略:
function findLinks(contentBlock, callback) {
const links = linkify.match(contentBlock.getText());
if (links) {
links.map(link => callback(link.index, link.lastIndex))
}
}
組件:
const Link = (props) => {
const editorState = props.getEditorState();
const contentState = editorState.getCurrentContent();
const selectionState = editorState.getSelection();
const contentStateWithEntity = contentState.createEntity(
'LINK',
'IMMUTABLE',
{ url: props.decoratedText }
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const contentStateWithLink = Modifier.applyEntity(
contentStateWithEntity,
selectionState,
entityKey
);
const entity = contentStateWithLink.getEntity(entityKey);
const { url } = entity.getData();
const type = entity.getType();
const newEditorState = EditorState.set(editorState, {
currentContent: contentStateWithEntity
});
props.setEditorState(newEditorState);
return <a href={url} target="_blank">{url}</a>;
};
我知道有問題的slectionState或檢索的文本塊並修改它而不是c reate一個新的實體,但我有點失落。我甚至使用正確的邏輯來做到這一點?
感謝您的幫助,
沒有你設法解決這個問題?我正面臨類似的問題。 – curial
不,我回顧了我的方法,因爲裝飾者與實體之間存在衝突。根據答案中的情況,我已經提出了兩種選擇。如果您同時需要,可以一起實施替代方案。 –