React: Script tag not working when inserted using dangerouslySetInnerHTML

后端 未结 5 1369
甜味超标
甜味超标 2020-11-28 12:29

I\'m trying to set html sent from my server to show inside a div using dangerouslySetInnerHTML property in React. I also have script tag inside it and use functions defined

5条回答
  •  天涯浪人
    2020-11-28 13:06

    I don't think you need to use concatenation (+) here.

    var x = 'alert("this.is.sparta");function pClicked() {console.log("p is clicked");}

    Hello

    ';

    I think you can just do:

    var x = '

    Hello

    ';

    Since it's passed to dangerouslySetInnerHTML anyway.

    But let's get back to the issue. You don't need to use regex to access the script tag's content. If you add id attribute, for example , you can easily access the element.

    Let's see an example of such implementation.

    const x = `
      
        
        
          

    Hello

    `; const Hello = React.createClass({ displayName: 'Hello', componentDidMount() { const script = document.getElementById('myScript').innerHTML; window.eval(script); } render() { return
    ; } });

    If you have multiple scripts, you can add a data attribute [data-my-script] for example, and then access it using jQuery:

    const x = `
      
        
        
        
          

    Hello

    `; const Hello = React.createClass({ constructor(props) { super(props); this.helloElement = null; } displayName: 'Hello', componentDidMount() { $(this.helloElement).find('[data-my-script]').each(function forEachScript() { const script = $(this).text(); window.eval(script); }); } render() { return (
    (this.helloElement = helloElement)} dangerouslySetInnerHTML={{__html: x}} /> ); } });

    In any case, it's always good to avoid using eval, so another option is to get the text and append a new script tag with the original's script contents instead of calling eval. This answer suggests such approach

提交回复
热议问题