2016-01-13 58 views
2

我有加載外部腳本的問題中反應JSX異步加載腳本中的反應成分

<script> 
    (function(d) { 
     var config = { 
       kitId: 1234567, 
       scriptTimeout: 3000, 
       async: true 
      }, 
      h=d.documentElement,t=setTimeout(function(){h.className=h.className.replace(/\bwf-loading\b/g,"")+" wf-inactive";},config.scriptTimeout),tk=d.createElement("script"),f=false,s=d.getElementsByTagName("script")[0],a;h.className+=" wf-loading";tk.src='https://use.typekit.net/'+config.kitId+'.js';tk.async=true;tk.onload=tk.onreadystatechange=function(){a=this.readyState;if(f||a&&a!="complete"&&a!="loaded")return;f=true;clearTimeout(t);try{Typekit.load(config)}catch(e){}};s.parentNode.insertBefore(tk,s) 
    })(document); 
</script> 

,這裏是我的渲染功能,在這裏我想有javascipt的負載ASYN,它在一個HTML文件超級簡單,但是我如何做到這一點在一個反應​​組件中驚呆了。 (如果我可以避免安裝另一個外部模塊將是最好的)。非常感謝

render() { 
    return (
     <head> 
      //Script to load asyn 
     </head> 
    ) 
} 
+0

你正在試圖做將不起作用怎麼辦。相反,請嘗試'componentDidMount()'內的以下策略之一:http://stackoverflow.com/questions/13121948/dynamically-add-script-tag-with-src-that-may-include-document-write – azium

+0

反應組件正在注入您的HTML? – hazardous

+0

是的,我不清楚你想要做什麼。你可以提供一個不起作用的小提琴嗎? –

回答

2

我的服務器呈現最初的HTML文檔,所以我不能像@mjhm建議的那樣將它插入到頭部。使用@ bluebill1049的回答,我能夠利用ES6模板字符串和反應的dangerouslySetInnerHTML

import React, {Component} from 'react'; 

export default class Html extends Component { 

    render() { 
    const loadTypeKit = ` 
     (function(d) { 

     var config = { 
      kitId: 'YOUR_KITID', 
      scriptTimeout: 3000, 
      async: true 
      }, 
      h=d.documentElement, 
      t=setTimeout(function() { 
      h.className=h.className.replace(/wf-loading/g,"")+" wf-inactive"; 
      },config.scriptTimeout), 
      tk=d.createElement("script"), 
      f=false, 
      s=d.getElementsByTagName("script")[0], 
      a; 

     h.className+=" wf-loading"; 
     tk.src='https://use.typekit.net/'+config.kitId+'.js'; 
     tk.async=true; 
     tk.onload=tk.onreadystatechange=function() { 
      a=this.readyState; 
      if(f||a&&a!="complete"&&a!="loaded") return; 
      f=true; 
      clearTimeout(t); 
      try{ 
      Typekit.load(config) 
      } catch(e){ } 
     }; 
     s.parentNode.insertBefore(tk,s); 

     })(document); 
     `; 

    return (
     <html> 
     <head> 
     <script dangerouslySetInnerHTML={{__html: loadTypeKit}} /> 
     </head> 
     <body> 
      ... 
     </body> 
     </html> 
    ); 
    } 
}