动态插入将通过Reactjs执行的脚本标记

Kel*_*gan 12 reactjs react-jsx

关于这一点有很多答案,但我正在寻找特定于reactjs的东西

我的组件代码:

  render: function () {

    return (
      <Modal {...this.props} title="Embed on your own site!">
        <div className="modal-body">
          <div className="tm-embed-container" dangerouslySetInnerHTML={{__html: embedCode}}>
          </div>
          <textarea className="tm-embed-code" rows="4" wrap="on" defaultValue={embedCode}></textarea>
        </div>
      </Modal>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

脚本标记在页面上,但没有执行.我是否应该做出反应,只是使用好的'DOM脚本',正如其他答案所示?

Bac*_*sme 10

根据我的理解,反应方式是使用"componentDidMount"函数在div中插入你想要的东西,包括一些外部脚本.

如果您的组件是动态的并且接收常规的新道具,那么您还应该考虑其他方法(例如componentDidUpdate).

有关此问题的 jQuery脚本插入的更多信息

  componentDidMount: function(){
    var embedCode = this.props.embedCode; // <script>//my js script code</script>
    
    $('#scriptContainer').append(embedCode);
    },

  render: function () {
    return (
      <Modal {...this.props} title="Embed on your own site!">
        <div className="modal-body">
          <div className="tm-embed-container" id="scriptContainer">
          </div>
          <textarea className="tm-embed-code" rows="4" wrap="on" defaultValue={this.props.embedCode}></textarea>
        </div>
      </Modal>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 我想避免jquery,对不起,我应该这么说.我最终使用了html(); (2认同)
  • 这有点神奇,显然jquery不仅仅是`const div = document.createElement('div');``div.innerHTML ='<script />';``document.getElementById('put_script_here').appendChild( div);`,但它有效 (2认同)