简体   繁体   English

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

[英]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,我知道我可以简单地使用 JSX 添加它,但我不知道如何使用它,

for instance this script has a function called A.Sort(), how can I call it and use it from a component?例如,此脚本有一个名为 A.Sort() 的 function,我如何调用它并从组件中使用它?

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 .它应该连接到window

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

or或者

scriptLoaded() {
  A.sort();
}

You can include the tag in the /public/index.html, and then use the script as you use it in normal JS code, following example for if you want to use jQuery:您可以在 /public/index.html 中包含该标签,然后像在普通 JS 代码中一样使用该脚本,如果您想使用 jQuery,请参考以下示例:

in your public/index.html include the following:在您的 public/index.html 中包含以下内容:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

And then anywhere you can use the jQuery functionality as usual:然后在任何地方您都可以像往常一样使用 jQuery 功能:

window.$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});

Sometimes we need to work with external js libraries in such cases we need to insert script tags into components, but in react we use jsx, so we can't add script tags directly just like how we add in HTML.有时我们需要使用外部js库,这种情况下我们需要在组件中插入script标签,但是在react中我们使用的是jsx,所以我们不能像在HTML中添加那样直接添加script标签。

In this example, we will see how to load an external script file into a head, body elements, or component.在这个例子中,我们将看到如何将外部脚本文件加载到头部、主体元素或组件中。

componentDidMount() {
    const script = document.createElement("script");
    script.async = true;
    script.src = "https://some-scripturl.js";
    script.onload = () => this.scriptLoaded();



    //For head
    document.head.appendChild(script);

    // For body
    document.body.appendChild(script);

    // For component
    this.div.appendChild(script);

  }

You can either modify your index.html file (if you are using one) by adding the required script.您可以通过添加所需的脚本来修改您的 index.html 文件(如果您正在使用)。

Alternatively, if you can't edit it or you are not using it, there's a bunch of add-ons that solve this, for example react-load-script或者,如果你不能编辑它或者你没有使用它,有一堆附加组件可以解决这个问题,例如react-load-script

You can use React Helmet npm你可以使用 React Helmet npm

step 1 : npm i react-helmet第 1 步: npm i react-helmet

step 2 :第2步 :

<Helmet>
    <script src="/path/to/resource.js" type="text/javascript" />
</Helmet>

After adding this script into your index.html将此脚本添加到 index.html 后

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

you might check the available functions if you console.log(window) in App.js (or, wherever you want).如果您在 App.js(或任何您想要的地方)中使用 console.log(window),您可能会检查可用的功能。 Once you check the exact function, then you can use it like一旦你检查了确切的功能,那么你就可以像这样使用它

window.A.sort();

I think this could be the simplest way.我认为这可能是最简单的方法。 Just remember that you have to write 'window.'请记住,您必须编写“窗口”。 on the left side of your function.在函数的左侧。

A hooks version.一个钩子版本。

import * as React from "react";

function loadError(onError) {
  console.error(`Failed ${onError.target.src} didn't load correctly`);
}

function External() {
  React.useEffect(() => {
    const LoadExternalScript = () => {
      const externalScript = document.createElement("script");
      externalScript.onerror = loadError;
      externalScript.id = "external";
      externalScript.async = true;
      externalScript.type = "text/javascript";
      externalScript.setAttribute("crossorigin", "anonymous");
      document.body.appendChild(externalScript);
      externalScript.src = `https://externalurl.example.com/external.js?key=9393ABCDEFGH`;
    };
    LoadExternalScript();
  }, []);

  return <></>;
}

export default External;

If you want to import script in multiple components, then you can create your own custom hook that allows you to insert script in desired component:如果你想在多个组件中导入脚本,那么你可以创建自己的自定义挂钩,允许你在所需组件中插入脚本:

import { useEffect } from 'react'
const importScript = src => {
  useEffect(() => {
    const script = document.createElement('script')
    script.src = src
    script.async = true
    document.body.appendChild(script)
    return () => {
      document.body.removeChild(script)
    }
  }, [src])
}
export default importScript

Using it on your desired component:在您想要的组件上使用它:

import importScript from 'import-path'
const DesiredComponent = props => {
  importScript("/path/to/resource")
  // ... rest of the code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM