reactjs - 在 React Router 中处理来自 Wordpress API 页面内容的静态链接
问题描述
我正在使用 Wordpress 作为无头 cms 使用 React Router 构建一个反应应用程序,但我遇到了一个问题,即我无法处理页面内容中的链接。我在 Wordpress 中编辑了从yourwebsite.com/about/
到的链接/about
,并且路由在前端工作,但它同时刷新了页面。有没有办法告诉路由器将这些静态内容链接视为路由?
解决方案
我react-html-parser
按照 cbr 在评论中的建议使用。实现转换功能的文档很少,所以下面是我完成它的方法:
export default function ContentBlock({
children, className, tagName
}) {
const Tag = tagName;
const domain = 'www.yourdomain.co.uk';
function transform(node) {
// convert <a> to React-Router <Link>
if (node.type === 'tag' && node.name === 'a') {
// Only apply the transform to internal links
if(node.attribs.href.indexOf(domain) > 0) {
const href = node.attribs.href.split(domain)[1].split('/')[1];
const classes = node.attribs.class ? node.attribs.class : '';
const label = node.children[0].data;
return <Link to={`/${href}`} className={classes}>{label}</Link>
}
}
}
return (
<Tag className={className} >
{ ReactHtmlParser(children, {transform}) }
</Tag>
)
}
推荐阅读
- linux - 在 bash_profile 中自定义 git 命令以自动索引到下一个分支
- java - 主题:使用回溯(而不仅仅是递归 DFS)背后的直觉
- forms - 使用 URL/查询字符串预填充输入表单值需要什么工作?
- apache-kafka - IoT - 多个 Kafka 生产者将消息发布到同一主题
- javascript - 当我使用 jquery 试图从另一个页面检索一些文本时,为什么我得到 [object Object]
- java - 使用 mongoClient 在 mongoDb 中插入日期
- android - 使用带有名称和密码的指纹身份验证登录
- openseadragon - 如何创建可缩放的文本
- delphi - 如何摆脱firemonkey中的圆圈中风
- angularjs - 仅允许减号作为第一个输入