首页 > 解决方案 > Draftjs:链接不起作用,呈现为普通文本

问题描述

我正在尝试将链接添加到我的 draftjs 编辑器。我首先选择要添加链接的文本,然后单击要求提供 URL 的按钮。很像 stackoverflow 自己的编辑器。

我正在将编辑器输出渲染为 markdown,并且我可以看到已添加了一个链接,因为 markdown 显示了典型的语法[selected text](added hyperlink),但在编辑器本身中,我添加超链接的选定文本仍然看起来像普通文本。

代码沙盒: https ://codesandbox.io/s/github/Suedo/MobX2020/tree/draftjs-test

有人可以帮我解决吗?

这是负责添加链接的处理程序方法:

  const addLink = () => {
    console.log('in addlink');
    const selectionState = editorState.getSelection();
    const link = window.prompt('Paste your link: ');
    if (!link) {
      // onEditorChange(RichUtils.toggleLink(editorState, selectionState, null));
      return;
    }
    const contentState = editorState.getCurrentContent();
    const contentStateWithEntity = contentState.createEntity('LINK', 'MUTABLE', {
      url: link,
    });

    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const contentStateWithLink = Modifier.applyEntity(contentStateWithEntity, selectionState, entityKey);
    const newEditorState = EditorState.set(editorState, {
      currentContent: contentStateWithLink,
    });

    onEditorChange(RichUtils.toggleLink(newEditorState, newEditorState.getSelection(), entityKey));
    return;
  };

其中 myonEditorChange是一个简单的方法,可以像这样设置 editorState:

  const onEditorChange = (newState: any) => {
    setEditorState((editorState) => newState);
  };

标签: reactjshyperlinkeditordraftjs

解决方案


推荐阅读