繁体   English   中英

在使用dangerouslySetInnerHtml呈现内容时如何使用React链接?

[英]How to use React links when rendering content with dangerouslySetInnerHtml?

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

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

但是,我在<a href='/'>Home Page</a>中添加的任何链接都不使用react路由器,而是触发重新加载页面。

有没有办法处理这个反应,而不必解析HTML并用<Link>替换<a>标签?

您可以在HTML容器上使用单击处理程序来捕获点击次数。 如果单击源自<a>标记(或子标记),则可以防止默认,并使用href

在这种情况下,您可以使用react-router的withRouter来获取history对象,并使用push方法通知路由器。 您也可以编辑网址,或以其他方式操纵网址。

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

 // 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM