本文介绍了可以使用React Helmet将javascript对象注入< HEAD>中.标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我需要向 HEAD 标签中插入一个javascript对象,以用于标签管理.这是我的头盔组件,但是它仅接受通过rewind()函数设置为元数据服务器端的特定参数.

还有没有办法使用React Helmet来完成我需要的工作,因此,可以在 SCRIPT 标签中创建javascritpt对象,还是应该采用其他方法?

MyComponent.js

 <头盔title = {article.get('title')}meta = {[{"property":"og:title","content":article.get('title')},{"property":"og:url","content":article.get('url')},{属性":"twitter:标题",内容":article.get('title')}]}/> 

server.js

 让htmlHead =`$ {head.title}$ {head.meta.toString()}`; 

感谢您的支持

解决方案

更新

2017年的这个答案适用于v3的react-helmet,现在已经有些过时了-现在,有一种更好的方法,直接使用script标签(如,我建议这样做.

将为后代以及使用较旧版本的头盔的人提供此答案.但请注意,尽管这是投票率最高的答案,但它不再是最佳答案.


您可以使用Helmet的 script 道具上的 innerHTML 属性在嵌入式脚本中定义对象-此属性在头盔3.0.0

 <头盔脚本= {[{类型:"text/javascript",innerHTML:'window.yourObject = {它:作品";}'}]}/> 

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

解决方案

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.


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" }' 
  }]} 
/>

这篇关于可以使用React Helmet将javascript对象注入&lt; HEAD&gt;中.标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 22:14