危险地渲染内容时如何使用React链接? [英] How to use React links when rendering content with dangerouslySetInnerHtml?
问题描述
因此,我正在为React应用程序开发一个博客页面.该页面正在从CMS加载数据,并且博客文章的内容是原始html,我在页面上使用以下内容呈现:
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:
< div危险地设置InnerHTML = {{____:this.state.content}}/>
但是我张贴在帖子中的任何链接< a href ='/'>首页</a>
不使用react router,而是触发重新加载页面.
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.
有没有一种方法可以解决此问题,而不必解析HTML并用< Link>
替换< a>
标记?
Is there a way to handle this in react without having to parse the HTML and replace <a>
tags with <Link>
?
推荐答案
您可以在HTML容器上使用点击处理程序来捕获点击.如果点击来自< a>
标记(或其子级),则可以阻止默认设置,并使用 href
.
You can use a click handler on the HTML container to catch clicks. If the click originates from an <a>
tag (or a childrn of), you can prevent default, and use the href
.
在这种情况下,您可以使用react-router的 withRouter
获取 history
对象,并使用 push
方法通知路由器.您还可以编辑该URL,或以其他方式对其进行操作.
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. 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>
这篇关于危险地渲染内容时如何使用React链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!