繁体   English   中英

ReactJS 与 LinkedIn API

[英]ReactJS with LinkedIn APIs

我正在处理需要使用 LinkedIn api 的反应项目。 我基本上想做和这里一样的事情: https://www.c-sharpcorner.com/blogs/fetch-linkedin-data-using-javascript

但是,在我的项目中,我只使用组件,我无法控制主机页面,所以我不能使用标签来引用linkedin api。 我所做的是这样的:

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

这实际上呈现了 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>  

我不确定如何在不更改实际主机页面的情况下将其转换为 React。 我们可以在组件级别上做到这一点吗?

不确定这是否可行,但您可以尝试为脚本 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);

使用 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