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
105 views
in Technique[技术] by (71.8m points)

javascript - How do I use external script that I add to react JS?

I would like to add to my react component a

<script>http://xxx.xxx/XX.js</script>

I know I can simply add it using JSX , what I don't know is how to use it,

for instance this script has a function called A.Sort() , how can I call it and use it from a component?

question from:https://stackoverflow.com/questions/53396307/how-do-i-use-external-script-that-i-add-to-react-js

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

1 Answer

0 votes
by (71.8m points)

You can load the script asynchronously and access it on load.

componentDidMount() {
  const script = document.createElement("script");
  script.src = "/static/libs/your_script.js";
  script.async = true;
  script.onload = () => this.scriptLoaded();

  document.body.appendChild(script);
}

It should get attached to the window.

 scriptLoaded() {
   window.A.sort();
 }

or

scriptLoaded() {
  A.sort();
}

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

...