问题
I would like to add a google custom search box in my site, which is created by using ReactJS. So the user can search content both within the site and on web.
The Google generated code is something like:
<script>
(function() {
var cx = '013626029679071:ze3ta4';
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>
Is there a way to add this into the React component? It keeps saying SyntaxError. I tried to create a component for the above code and use it in the React Component, but nothings shows up. Is this the right way to add a searchbar on React site? Any hints?
Thanks!
回答1:
This perfectly works for me. Add a form element in your react and modify the snippet as shown below. react return. Add a form element tag try it. it works for me.
<form method = "get" title = "Search Form" action="https://cse.google.com/cse/publicurl">
<div>
<input type="text" id="q" name="q" title="Search this site" alt="Search Text" maxlength="256" />
<input type="hidden" id="cx" name="cx" value="013626029654558379071:ze3tw4csia4" />
<input type="image" id="searchSubmit" name="submit" src="https://www.flaticon.com/free-icon/active-search-symbol_34148" alt="Go" title="Submit Search Query" />
</div>
</form>
回答2:
I think I have a solution for you without using dangerouslySetInnerHTML. Put your code in the componentDidMount block and append to the element with jQuery like so:
componentDidMount(){
const embedcode = `<script>
(function() {
var cx = '013626029654558379071:ze3tw4csia4';
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>`
$('#gsearch').html(embedcode)
}
And your DOM element:
<div id='gsearch'>
</div>
Still debugging some styling stuff, but this works!
Best, Patrick
来源:https://stackoverflow.com/questions/41577801/how-to-include-google-custom-search-box-in-an-react-component