How to use React links when rendering content with

2020-06-18 01:47发布

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

Is there a way to handle this in react without having to parse the HTML and replace <a> tags with <Link>?

1条回答
Viruses.
2楼-- · 2020-06-18 02:41

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.

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>

查看更多
登录 后发表回答