如何在React App中嵌入Google自定义搜索?

时间:2018-12-10 17:11:29

标签: javascript reactjs google-custom-search

我需要在React应用程序中嵌入JS小部件。有办法吗?

JS小部件是Google自定义搜索:

  (function() {
    var cx = '111:xxx';
    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);
  })();
<gcse:search></gcse:search>

1 个答案:

答案 0 :(得分:8)

使用conponentDidMount

conponentDidMount() {
  (function() {
    var cx = '111:xxx';
    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);
  })();
}

并使用

<div class="gcse-searchbox" data-resultsUrl="http://www.example.com"
data-newWindow="true" data-queryParameterName="search" />`

代替documentation<gcse:search></gcse:search>