2017-04-24 34 views
1

創建裝飾鏈路實體我使用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一個新的實體,但我有點失落。我甚至使用正確的邏輯來做到這一點?

感謝您的幫助,

+0

沒有你設法解決這個問題?我正面臨類似的問題。 – curial

+0

不,我回顧了我的方法,因爲裝飾者與實體之間存在衝突。根據答案中的情況,我已經提出了兩種選擇。如果您同時需要,可以一起實施替代方案。 –

回答

0

我已經看到了正在建設<a>標籤與裝飾反應草案仍然這一特定問題沒有解決方案必須對它們進行編輯,而無需衝突的可能性。

然而,這裏有兩種選擇:

  1. 創建鏈接的實體時,選擇文本,然後點擊鏈接按鈕 ,因爲它是詳見反應例如草案。

  2. 使用裝飾器在您的編輯器中顯示鏈接,然後在提交時, 通過檢索鏈接並將其替換爲<a>標籤來編輯您的內容。 在所有情況下,我仍然認爲您需要清理內容服務器端的安全問題。利用這一點,可能會縮短您的鏈接。


第一個解決方案是,當你創建文章或博客內容更適合。 當您使用郵件系統的草稿時,第二個更方便。