簡體   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