添加GTM脚本以响应组件RendertoString

时间:2017-06-15 04:07:13

标签: javascript reactjs

我正在使用Isomorphic React应用程序来呈现页面。我必须将GTM脚本添加到页面中,当我添加到java脚本文件时,babel由于引号和其他东西而失败,我可能知道如何逃脱或确保babel跳过此。它在redertoString函数

中失败了
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->

1 个答案:

答案 0 :(得分:1)

您可以使用React&#39; s dangerouslySetInnerHTML

来实现 像这样

<script
  type="text/javascript"
  dangerouslySetInnerHTML={{
    __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
      new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
      j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
      'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
      })(window,document,'script','dataLayer','GTM-XXXX');`
  }}
/>