【问题标题】:How to add space character after hyperlink in DraftJS?如何在 DraftJS 中的超链接后添加空格字符?
【发布时间】:2016-11-07 16:24:43
【问题描述】:

我在使用 DraftJS API 实现以下场景时遇到问题。

这是场景: 按照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,然后他在提示符中为其提供了网址,例如http://yahoo.com 文字abc转超链接,好酷。

但是在文本编辑器中的光标立即滑到行首之后。当用户手动尝试将该光标移动到行尾并再次键入内容时,文本编辑器会在行首显示键入的文本,这很奇怪。

在我看来,应该在生成的超链接之后插入一个空格字符,以便用户能够在此之后输入一些内容。光标也必须停留在超链接的末尾而不是行首。

我怎样才能做到这一点?

【问题讨论】:

    标签: reactjs hyperlink draftjs


    【解决方案1】:

    好的,我玩了很久找到了答案。

    首先,我必须将我的选择折叠到转换后的链接的末尾,然后使用修饰符插入一个空格字符。

    代码如下:

    _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);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 2018-09-25
      • 1970-01-01
      • 2017-03-20
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      相关资源
      最近更新 更多