Adding script tag to React/JSX

后端 未结 17 943
感动是毒
感动是毒 2020-11-22 03:52

I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:

\'use strict\';

import \'../../styles/         


        
17条回答
  •  终归单人心
    2020-11-22 04:40

    Further to the answers above you can do this:

    import React from 'react';
    
    export default class Test extends React.Component {
      constructor(props) {
        super(props);
      }
    
      componentDidMount() {
        const s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.innerHTML = "document.write('This is output by document.write()!')";
        this.instance.appendChild(s);
      }
    
      render() {
        return 
    (this.instance = el)} />; } }

    The div is bound to this and the script is injected into it.

    Demo can be found on codesandbox.io

提交回复
热议问题