如何在React Quill中为话题标签和@提及添加自定义跳转链接
quill-mention 自定义@提及和话题标签跳转链接实现方案
步骤1:修复Link sanitize逻辑,适配内部相对路径
你当前的Link sanitize逻辑会给所有非http/https开头的路径强制加http前缀,会导致你需要的内部路由路径/#/xxx跳转异常,先调整这部分逻辑:
const Link = Quill.import("formats/link"); Link.sanitize = function (url) { // 放过内部相对路径、哈希路径 if (url.startsWith("/") || url.startsWith("#")) { return url; } if (!url.startsWith("http://") && !url.startsWith("https://")) { return `http://${url}`; } return url; };
步骤2:将linkTarget改为函数类型,动态生成不同类型的跳转链接
quill-mention的linkTarget参数支持传入函数,会接收当前选中的条目对象、触发字符两个入参,你可以根据触发字符的不同返回对应的跳转路径,修改后的mention配置如下:
const mention = { allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/, mentionDenotationChars: ["@", "#"], // 替换原来的固定字符串为动态生成函数 linkTarget: function(item, mentionChar) { if (mentionChar === "@") { return `/#/people/${item.id}`; } else if (mentionChar === "#") { return `/#/hashtags/${item.id}`; } return ""; }, source: function (searchTerm, renderList, mentionChar, ) { let values; if (mentionChar === "@") { values = atValues; } else { values = hashValues; } if (searchTerm.length === 0) { renderList(values, searchTerm); } else { const matches = []; for (let i = 0; i < values.length; i++) if (~values[i].value.toLowerCase().indexOf(searchTerm.toLowerCase())) matches.push(values[i]); renderList(matches, searchTerm); } }, };
修改完成后,插入的@提及会自动生成<a href="/#/people/对应id">@对应用户名</a>格式的标签,话题标签会生成<a href="/#/hashtags/对应id">#对应话题名</a>格式的标签,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者Suraj Pawar
相关产品推荐
相关产品推荐

