2016-11-04 144 views
2

我在使用DraftJS API實現以下方案時遇到了問題。如何在DraftJS中的超鏈接後添加空格字符?

下面是這種情況: 繼提供this

我使用下面的代碼,當用戶確認的超級鏈接URL後選定的文本超鏈接轉換鏈接例如:

_confirmLink(urlValue) { 
    const {editorState} = this.state; 
    const entityKey = Entity.create('LINK', 'MUTABLE', {url: urlValue}); 

    this.setState({ 
     showURLInput: false, 
     editorState: RichUtils.toggleLink(
     editorState, 
     editorState.getSelection(), 
     entityKey 
    ) 
    },() => 
     setTimeout(() => this.refs.editor.focus(), 100); 
    }); 
} 

現在假設用戶輸入了文字abc,然後他在提示中提供了url,例如http://yahoo.com 文字abc轉換爲超鏈接,很酷。

但之後,文本編輯器中的光標立即滑動到行首。當用戶手動嘗試將該光標移動到行尾並再次輸入某些內容時,文本編輯器會在行首顯示輸入的文本,這很奇怪。

在我看來,應該在生成的超鏈接之後插入空格字符,以便用戶能夠在此之後鍵入內容。遊標也必須停留在超鏈接的末尾,而不是在行首。

我該如何做到這一點?

回答

1

好的,我在玩了很長時間後找到了答案。

基本上首先,我必須將我的選擇合併到轉換後的鏈接的末尾,然後使用Modifier I在此之後插入一個空格字符。

下面的代碼:

_confirmLink(urlValue) { 

    const {editorState} = this.state; 

    const entityKey = Entity.create(
     'LINK', 
     'MUTABLE', 
     {url: urlValue} 
    ); 

    let selection = editorState.getSelection(); 

    const contentState = Modifier.applyEntity(
     editorState.getCurrentContent(), 
     selection, 
     entityKey 
    ); 

    let linked = EditorState.push(
     editorState, 
     contentState, 
     'apply-entity' 
    ); 

    let collapsed = selection.merge({ 
         anchorOffset: selection.getEndOffset(), 
         focusOffset: selection.getEndOffset() 
         }); 

    let newEditorState = EditorState.forceSelection(linked, collapsed); 

    this.setState({ 
     showURLInput: false, 
     editorState: newEditorState 
    },() => { 
     setTimeout(() => { 

     this.refs.editor.focus(); 

     const {editorState} = this.state; 
     let selection = editorState.getSelection(); 

     let cs = Modifier.insertText(
      editorState.getCurrentContent(), 
      selection, 
      ' ' 
     ); 

     const newEditorState = EditorState.push(
      editorState, 
      cs, 
      'insert-text' 
     ); 

     this.setState({editorState: newEditorState}); 
     }, 10); 
    }); 
} 
相關問題