问题
I've a question, I need to inject into the HEAD tag a javascript object, for tag management purposes. This is my Helmet component, but it accepts only specific parameters to set to metadata serverside through rewind() function.
Is there a way still to use React Helmet to do what I need, so, create javascritpt objects into a SCRIPT tag or should I follow a different approach?
MyComponent.js
<Helmet
title={article.get('title')}
meta={[
{"property": "og:title", "content": article.get('title')},
{"property": "og:url", "content": article.get('url')},
{"property": "twitter:title", "content": article.get('title')}
]}
/>
server.js
let htmlHead = `
${head.title}
${head.meta.toString()}
`;
Thank you for the support
回答1:
Update
This answer from 2017 applies for v3 of react-helmet, and is now a little outdated - there's now a better way to do this, using a script tag directly, as referenced in a newer answer, which I'd recommend doing instead.
Will keep this answer up for posterity, and for people on older versions of Helmet. But just a note that though it's the top voted answer, it's no longer the best answer.
I need to inject into the HEAD tag a javascript object
You could define the object in an inline script, using the innerHTML
attribute on Helmet's script
prop - this attribute was introduced in Helmet 3.0.0
<Helmet
script={[{
type: 'text/javascript',
innerHTML: 'window.yourObject = { it: "works" }'
}]}
/>
回答2:
If I understood your question correctly, in your <Helmet/>
declaration, you can add in a script
property to inject a <script>
tag into the HTML head of your pages.
<Helmet
title={article.get('title')}
meta={[
{"property": "og:title", "content": article.get('title')},
{"property": "og:url", "content": article.get('url')},
{"property": "twitter:title", "content": article.get('title')}
]}
script={[
{"src": "http://url.com/script.js", "type": "text/javascript"}
]}
/>
回答3:
Th existing answers are outdated. You don't need to contort the code with script
attributes or innerHTML
. You can use the <script>
tag as usual in HTML:
<Helmet>
<script src="https://some.host/api.js" type="text/javascript" />
</Helmet>
来源:https://stackoverflow.com/questions/37922183/can-react-helmet-inject-a-javascript-object-into-head-tag