[英]How can I replace bits or string with React component, react-router-dom Link or an anchor tag <a></a>
How can I replace bits of string with links or components如何用链接或组件替换字符串位
This is a sample of the data这是数据样本
Ownership of Product/DiJUHl5zCE changed from Org/abcd to Org/efghi
Stage changed to completed for Payment of 254.15 gbp on Cycle Cycle/svgAjnox5t
Ownership of Product/DSGDHFHFDH changed from Org/sdef to Org/juhtr
Stage changed to completed for Payment of 4.15 gbp on Cycle Cycle/fdlkgdfkjdfl
I want to replace我想换
Ownership of Product/DiJUHl5zCE changed from Org/dvju to Org/kijuy Product/DiJUHl5zCE 的所有权从 Org/dvju 更改为 Org/kijuy
Ownership of Product changed from OrgName to OrgName产品的所有权从OrgName更改为OrgName
Ownership of <a href="/product/Product/DiJUHl5zCE">Product</a> changed from <a href="/org/Org/abcd">OrgName</a> to <a href="/org/Org/efghi">OrgName</a>
and和
Stage changed to completed for Payment of 254.15 gbp on Cycle Cycle/svgAjnox5t在 Cycle Cycle/svgAjnox5t 上支付 254.15 gbp 的阶段更改为已完成
Stage changed to completed for Payment of 254.15 gbp on Cycle Cycle在 Cycle Cycle支付 254.15 gbp 的阶段更改为已完成
Stage changed to completed for Payment of 254.15 gbp on Cycle <a href="/cycle/Cycle/svgAjnox5t">Cycle</a>
I also have a regex我也有一个正则表达式
/([\w\d]+)\/([\w\d-]+)/g;
https://regex101.com/r/VrqlI7/1 https://regex101.com/r/VrqlI7/1
that returns the groups but if I use replace() or replaceAll() the second argument returns string and in the browser it comes out as [object, object]返回组,但如果我使用 replace() 或 replaceAll() 第二个参数返回字符串,并在浏览器中显示为 [object, object]
basically pass each line through a function and return a div with bits of text replaced with links基本上通过 function 传递每一行并返回一个 div 用链接替换的文本位
I am relatively new to react.我是比较新的反应。 any help much appriciated.
任何帮助都非常感谢。
If I use `` at the start如果我在开始时使用 ``
if I use `` withing the href如果我使用 `` with the href
How can I get this to display as links, Please advice我怎样才能让它显示为链接,请指教
You can use replaceAll
with a callback您可以将
replaceAll
与回调一起使用
s.replaceAll(/([\w\d]+)\/([\w\d-]+)/g, (a) => {
if (a.startsWith("Product")) { return `<a href="/product/${a}">${a}</a>` }
else if (a.startsWith("Org")) { return `<a href="/org/${a}">${a}</a>` }
else { return a }
})
Edit: If you want to render links as react components, you can split the text by pattern using split()
and then map()
over the resulting array to replace the parts you need, like this:编辑:如果您想将链接呈现为反应组件,您可以使用
split()
按模式拆分文本,然后在结果数组上使用map()
以替换您需要的部分,如下所示:
const lPrefixMap = { 'Product': '/product/', 'Cycle': '/cycle/', 'Org': '/org/' };
const renderedContent = text.split(/([\w\d]+\/[\w\d-]+)/g).map((v, idx) => {
if (idx & 1) {
const linkType = v.split('/')[0];
const prefix = lPrefixMap[linkType];
return (<Link to={`${prefix}${v}`}>{v}</Link>);
}
return <span>v</span>;
});
// You can then render this in your JSX code like this:
return <div>{renderedContent}</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.