简体   繁体   English

ReactJS 与 LinkedIn API

[英]ReactJS with LinkedIn APIs

I am working on react project where I need to use the LinkedIn apis.我正在处理需要使用 LinkedIn api 的反应项目。 I basically want to do the same as done here: https://www.c-sharpcorner.com/blogs/fetch-linkedin-data-using-javascript我基本上想做和这里一样的事情: https://www.c-sharpcorner.com/blogs/fetch-linkedin-data-using-javascript

However, in my project, I only work with components, I don't have control over the host page, so I can't use tags to reference the linkedin apis.但是,在我的项目中,我只使用组件,我无法控制主机页面,所以我不能使用标签来引用linkedin api。 What I did was this:我所做的是这样的:

var script = document.createElement('script');
script.setAttribute('src','https://platform.linkedin.com/in.js');
document.head.appendChild(script);

Which actually renders the JS file for the api, however, how can I do the step mentioned in the article like this:这实际上呈现了 api 的 JS 文件,但是,我该如何执行文章中提到的步骤:

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
   api_key: XXXXXXX //Client ID  
   onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
   authorize: true  
</script>  

I am not sure how to translate this to React without having to change the actual host page.我不确定如何在不更改实际主机页面的情况下将其转换为 React。 Can we do this on the components level?我们可以在组件级别上做到这一点吗?

Not sure if this will work but you could try setting the innerHTML value for the script dom object不确定这是否可行,但您可以尝试为脚本 dom object设置 innerHTML 值

var script = document.createElement('script');
script.setAttribute('src','https://platform.linkedin.com/in.js');
script.innerHTML = `
   api_key: XXXXXXX //Client ID  
   onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
   authorize: true  
`;
document.head.appendChild(script);

Make use of componentDidMount to attach the script or useEffect.使用 componentDidMount 附加脚本或 useEffect。


    import { useEffect, useState } from "react";
    
    const API_KEY = "XXXXX";
    
    export default function App() {
      const [scriptLoaded, setScriptLoaded] = useState(false);
    
      useEffect(() => {
        const script = document.createElement("script");
        script.async = true;
        script.src = "https://platform.linkedin.com/in.js";
        script.innerHTML = `
         api_key: ${API_KEY},
         onLoad: "", // Use eventListiner instead of this
         authorize: true,
        `;
        document.head.appendChild(script);
        script.addEventListener("load", () => {
          // added your logic here.
          setScriptLoaded(true);
        });
      }, []);
    
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
          {scriptLoaded
            ? "Yes!!! script has loaded"
            : "No@@@@ Script has not yet loaded"}
        </div>
      );
    }

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

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