Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - Render script tag in React Component

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>
    );
  }
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...