我正在使用 Facebook Draft.js,当在文本中检测到有效网址时,我需要创建一个 LINK 实体。
目前,我正在使用装饰器来实现检测文本中是否有链接的策略,例如 Draft-js-linkify-plugin,但我在将该文本修改为不可变的 LINK 实体时遇到了一些麻烦。
确实,我用编辑器 Prop 进行装饰,但无法修改编辑器的状态,因此,应用这个新的 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 或检索文本 block 并修改它而不是创建新实体存在问题,但我有点迷失。我是否使用了正确的逻辑来做到这一点?
感谢您的帮助,
最佳答案
我还没有看到针对正在构建的这个特定问题的解决方案 <a>
在 React Draft 中使用装饰器标记,并且仍然可以在不发生冲突的情况下编辑它们。
但是,这里有两种选择:
选择文本并单击链接按钮时创建链接实体 正如 react 草案示例中详细介绍的那样。
使用装饰器在编辑器中显示链接,然后在提交时, 通过检索链接并将其替换为
<a>
来编辑您的内容标签。 在所有情况下,我仍然认为出于安全考虑,您需要清理内容服务器端。利用这一点,也许可以缩短您的链接。
第一个解决方案更适合您创建文章或博客内容。 当您使用消息系统草稿时,第二种更方便。
关于javascript - 如何在 Facebook Draft.js 中使用装饰器创建 Link 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43588183/