代码之家  ›  专栏  ›  技术社区  ›  Adam

在用危险的lysetinnerhtml呈现内容时如何使用react链接?

  •  4
  • Adam  · 技术社区  · 7 年前

    所以我正在为一个React应用程序开发一个博客页面。该页面正在从CMS加载数据,博客文章的内容是原始HTML,我在页面上呈现的是:

    <div dangerouslySetInnerHTML={{__html: this.state.content}} />

    不管我在帖子里放了什么链接 <a href='/'>Home Page</a> 不要使用react路由器,而是触发重新加载页面。

    有没有一种方法可以在不需要解析HTML和替换的情况下在React中处理这个问题? <a> 带标签 <Link> ?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Ori Drori    7 年前

    您可以使用HTML容器上的单击处理程序来捕获单击。如果单击源于 <a> 标记(或子标记),可以防止默认值,并使用 href .

    在这种情况下,您可以使用React路由器 withRouter 得到 history 对象,并使用 push 通知路由器的方法。您还可以编辑该URL,或以其他方式对其进行操作。

    示例(使用代码时取消注释并删除控制台):

    // import { withRouter } from 'react-router-dom'
    
    class HTMLContent extends React.Component {
      contentClickHandler = (e) => {
        const targetLink = e.target.closest('a');
        if(!targetLink) return;
        e.preventDefault();
        
        console.log(targetLink.href); // this.props.history.push(e.target.href)
      };
      
      render() {
        return (
          <div 
            onClick={this.contentClickHandler}
            dangerouslySetInnerHTML={{__html: this.props.content}} 
          />
        );
      }
    }
    
    // export default withRouter(HTMLContent);
    
    const content = `<div>
      <a href="http://www.first-link.com">Link 1</a>
      <a href="http://www.second-link.com"><span>Link 2</span></a>
    </div>`;
    
    ReactDOM.render(
      <HTMLContent content={content} />,
      demo
    );
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    
    <div id="demo"></div>