【问题标题】:Dynamically insert script tag that will execute via Reactjs动态插入将通过 Reactjs 执行的脚本标签
【发布时间】:2016-01-31 12:09:40
【问题描述】:

对此有很多答案,但我正在寻找特定于 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>
    );
  }
});

脚本标签在页面上,但没有执行。我是否应该像其他答案所表明的那样,不做反应,只使用良好的 DOM 脚本?

【问题讨论】:

    标签: reactjs react-jsx


    【解决方案1】:

    据我了解,反应方式是使用“componentDidMount”函数在 div 中插入您想要的内容,包括一些外部脚本。

    如果您的组件是动态的并且定期接收新的道具,您还应该考虑其他方法(如 componentDidUpdate)。

    更多关于在this question上使用 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>
        );
      }
    });

    【讨论】:

    • 想避免使用 jquery,抱歉我应该这么说。我最终使用了 html();
    • 这有点神奇,显然 jquery 不仅仅是 const div = document.createElement('div'); div.innerHTML = '&lt;script/&gt;'; document.getElementById('put_script_here').appendChild(div);,但它确实有效
    • 注意,如果外部脚本做document.write,你还有另一个问题:stackoverflow.com/a/2360112/6962
    猜你喜欢
    • 2017-01-21
    • 2019-02-13
    • 2020-07-13
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2020-02-01
    • 1970-01-01
    相关资源
    最近更新 更多