本文介绍了在React Component中渲染脚本标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个React应用程序,我只需要在一个组件中运行Javascript脚本,并引用div之一.

I'm making a React application and I need to run a Javascript script only in one component, making reference to one of the div's.

我知道有一些这样做的库,但是我想知道是否有更直接的方法来做到这一点.现在,我这样做:

I know there are some libraries to do so, but I wonder if there's a more direct way to do it. Right now I do this:

import React, { Component } from "react";
import "../ThisComponent.css";

export default class MyComponent extends Component {
  render() {
    return (
      <div>
        <div id="scriptTarget" />
        <div className="main">
          // Other stuff
        </div>
        <script src="js/myScript.js" />
      </div>
    );
  }
}

但是什么也没发生.脚本存储在public/js/myScript.js中.
谢谢!

But nothing happens. The script is stored in public/js/myScript.js.
Thanks!

推荐答案

我最终在渲染组件之前通过添加componentDidMount函数解决了它.像这样:

I finally solved it by adding the componentDidMount function before rendering the component. Like this:

import React, { Component } from "react";
import "../ThisComponent.css";

export default class MyComponent extends Component {
  componentDidMount() {
    const script = document.createElement("script");

    script.src = "js/myScript.js";
    script.async = true;

    document.body.appendChild(script);
  }

  render() {
    return (
      <div>
        <div id="scriptTarget" />
        <div className="main">
          // Other stuff
        </div>
      </div>
    );
  }
}

如果有人有更好的解决方案,请随时分享.我会通知您进一步的建议.

If somebody has a better solution please feel free to share it. I'll be aware to further recomendations.

这篇关于在React Component中渲染脚本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:18