简体   繁体   中英

How to connect raw html <a href> tag to React javascript?

I building out a small web app that simulates browsing WikiPedia by pulling raw html WikiPedia article content (via it's api). I'm then displaying the html in my app by using "dangerouslySetInnerHTML".

I trying to figure out how to allow a user to click on a an unmounted < ahref="wiki/javascript" > tag and capture that event on the React side. I wanted to capture that tag click to update UI state and make server requests.

When using "dangerouslySetInnerHTML" click events are not recognized by react. So I added a function on the global window object on the React side to be clicked on by the tags but get a warning about 'unmounted components' and 'memory leaks'.

How can I prevent the raw unmounted tags from reloading the page and capture that click event in order to update my React's UI?

I think there might be a better way to do what you're trying to do, but with your current implementation:

You can grab a ref on the node that you're doing dangerouslySetInnerHTML, add a click event listener, use event bubbling to capture that link event and finally invoke preventDefault() .

class App extends Component {

    componentDidMount(){
      if(this.myRef){
        this.myRef.addEventListener('click', this.anchorLinkListener);
      }
    }

    componentWillUnmount(){
      if(this.myRef){
         this.myRef.removeEventListener('click', this.anchorLinkListener)
      }
    }

    anchorLinkListener = (e) => {
       if(e.target.tagName === 'A') {
          console.log('Anchor link clicked')
          e.preventDefault();
       }
    }

    render(){
      return (
        <div 
          ref={(ref) => {this.myRef = ref}}
          dangerouslySetInnerHTML={{__html: '<a href="http://stackoverflow.com">click me</a>'}}
        />
      )
    }
}

So I am kind of looking at the problem from another angle.

I am thinking "hmm, dangerouslySetInnerHTML sounds rather ominous, as if I probably shouldn't use it. I wonder if there are nicer, safer alternatives...".

After doing a quick google search for "alternative to dangerouslySetInnerHTML" one of the promising results is this Medium article .

TLDR; we can do cool things with packages like HTML React Parser and that may solve our problem of not being able to capture events properly.

If we have access to the event object once again, we should be able to read its attributes and do whatever else we need to do

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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