Reactjs动态插入脚本标签并执行

12

这里有很多关于这个问题的答案,但我正在寻找特定于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>
    );
  }
});
1个回答

10
根据我的理解,使用React的做法是通过“componentDidMount”函数将所需内容插入div中,包括一些外部脚本。如果你的组件是动态的并且经常接收新的props,那么你还应该考虑其他方法(如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>
    );
  }
});


2
我想避免使用jQuery,抱歉我应该早点说。最终我使用了html()。 - Kelly Milligan
2
这有点神奇,显然jQuery不仅仅可以执行 const div = document.createElement('div'); div.innerHTML = '<script/>'; document.getElementById('put_script_here').appendChild(div);,但它确实有效。 - Sida Zhou
1
请注意,如果外部脚本执行了 document.write 操作,那么您就会遇到另一个问题:https://dev59.com/mXE95IYBdhLWcg3wUcRn#2360112 - Henrik N

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接