小编典典

如何使用添加的外部脚本来响应JS?

reactjs

我想添加到我的反应组件

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

我知道我可以简单地使用JSX添加它,但我不知道如何使用它,

例如,此脚本具有一个称为A.Sort()的函数,如何调用它并从组件中使用它?


阅读 301

收藏
2020-07-22

共1个答案

小编典典

您可以异步加载脚本并在加载时访问它。

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

  document.body.appendChild(script);
}

它应该附加到window

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

要么

scriptLoaded() {
  A.sort();
}
2020-07-22