首页 > 解决方案 > 在 React Router 中处理来自 Wordpress API 页面内容的静态链接

问题描述

我正在使用 Wordpress 作为无头 cms 使用 React Router 构建一个反应应用程序,但我遇到了一个问题,即我无法处理页面内容中的链接。我在 Wordpress 中编辑了从yourwebsite.com/about/到的链接/about,并且路由在前端工作,但它同时刷新了页面。有没有办法告诉路由器将这些静态内容链接视为路由?

标签: reactjswordpressreact-router

解决方案


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>
  )
}

推荐阅读