Consider a string "Foo #bar baz #fuzz". I want to display a "Caption" component in NextJS where the hashtags are hyperlinks.
My current approach is:
import Link from "next/link";
const handleHashTag = str =>
str
.split(" ")
.map(el => {
const r = /(.*)(#[^ ]*)/;
const matched = el.match(r);
if (matched)
return `<span>${matched[1]}</span><Link href="${matched[2]}"><a>${matched[2]}</a></Link>`;
return el;
})
.join(" ");
function Caption(catption) {
const linkedCaption = handleHashtag(caption)
return <div dangerouslySetInnerHTML={__html: }>
}
Corrosponding HTML has empty span
tags in place of <Link>
. This approach does relies on dangerouslySetInnerHTML. Is there a way to implement the functionality of <Link>
without using dangerouslySetInnerHTML
?
如果有匹配项,则返回一个组件,而不是字符串(基本上没有反引号和美元),并且不加入数组而是使用 jsx 中的 map 渲染其中的元素
A solution like react-hashtag addresses this problem. Instead of using react-router
as its source uses, you can use your custom Link component, in this case next/link
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.