2017-09-08 104 views
0

我想在我的React應用程序中使用谷歌自定義搜索引擎。但是我有一個應用它的問題。谷歌自定義搜索引擎 - 使用ReactJS

我在谷歌網站上覈對代碼是

<script> 
    (function() { 
    var cx = '008391824253360889328:j5posmpyok0'; 
    var gcse = document.createElement('script'); 
    gcse.type = 'text/javascript'; 
    gcse.async = true; 
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; 
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(gcse, s); 
    })(); 
</script> 
<gcse:search></gcse:search> 

但我不知道如何把它變成JSX可以使用反應。

任何人都可以幫忙嗎?謝謝。

回答

0

你不需要改變任何東西。你可以直接運行它。

例如:

conponentDidMount() { 
    (function() { 
    var cx = '008391824253360889328:j5posmpyok0'; 
    var gcse = document.createElement('script'); 
    gcse.type = 'text/javascript'; 
    gcse.async = true; 
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; 
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(gcse, s); 
    })(); 
} 

但實際上,如果您檢查您從谷歌獲得的代碼;它只是添加一個腳本標籤。你也可以手動添加它。

<script async="true" src="https://cse.google.com/cse.js?cx=008391824253360889328:j5posmpyok0" type="text/javascript"></script> 
+0

感謝。 此外,如何將這樣的添加到JSX中的render()函數中。因爲「」是xml,不能在jsx中使用。 –

+0

@VictorDiao我有兩個選擇。一個描述[這裏](https://stackoverflow.com/a/44012269/2315280)說你可以使用[dangerouslySetInnerHTML](https://facebook.github.io/react/docs/dom-elements.html# dangerouslysetinnerhtml),但它的危險。第二個是[這裏](https://developers.google.com/custom-search/docs/element#html5),您可以使用Html5 div標籤進行搜索。 – bennygenel