Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...