[英]How to use React links when rendering content with dangerouslySetInnerHtml?
So I'm developing a blog page for a react application. 所以我正在为反应应用程序开发一个博客页面。 The page is loading data from a CMS and the content of the blog post is raw html which I render on the page with:
页面正在从CMS加载数据,博客帖子的内容是原始html,我在页面上呈现:
<div dangerouslySetInnerHTML={{__html: this.state.content}} />
However any links I put in the post like <a href='/'>Home Page</a>
don't use react router and instead trigger reloading the page. 但是,我在
<a href='/'>Home Page</a>
中添加的任何链接都不使用react路由器,而是触发重新加载页面。
Is there a way to handle this in react without having to parse the HTML and replace <a>
tags with <Link>
? 有没有办法处理这个反应,而不必解析HTML并用
<Link>
替换<a>
标签?
You can use a click handler on the HTML container to catch clicks. 您可以在HTML容器上使用单击处理程序来捕获点击次数。 If the click originates from an
<a>
tag (or a childrn of), you can prevent default, and use the href
. 如果单击源自
<a>
标记(或子标记),则可以防止默认,并使用href
。
In this case, you can use react-router's withRouter
to get the history
object, and to use the push
method to notify the router. 在这种情况下,您可以使用react-router的
withRouter
来获取history
对象,并使用push
方法通知路由器。 You can also edit the url, or manipulate it in other ways. 您也可以编辑网址,或以其他方式操纵网址。
Example (uncomment and remove the console when you use the code): 示例(在使用代码时取消注释并删除控制台):
// 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.