【问题标题】:add raw HTML with <script> inside Gatsby React page在 Gatsby React 页面中添加带有 <script> 的原始 HTML
【发布时间】:2018-08-04 14:36:14
【问题描述】:

我正在尝试将外部嵌入代码添加到我的 Gatsby 页面。

我现在用

import React from 'react'
import Link from 'gatsby-link'


let test ="<script type='text/javascript'>
(function(d, s) {
    var useSSL = 'https:' == document.location.protocol;
    var js, where = d.getElementsByTagName(s)[0],
    js = d.createElement(s);
    js.src = (useSSL ? 'https:' : 'http:') +  '//www.peopleperhour.com/hire/1002307300/1213788.js?width=300&height=135&orientation=vertical&theme=light&rnd='+parseInt(Math.random()*10000, 10);
    try { where.parentNode.insertBefore(js, where); } catch (e) { if (typeof console !== 'undefined' && console.log && e.stack) { console.log(e.stack); } }
}(document, 'script'));
</script>"

const ContactPage = () => (

    <div>
        <h1>ContactPage</h1>
        <div
            dangerouslySetInnerHTML={{ __html: test }}
          />
    </div>

)

export default ContactPage

里面充满了语法错误。能否请您指出一种在反应组件中包含原始 sn-ps 的更好方法?

在 Gatsby 中是否还有一个地方可以添加所有其他脚本,例如自定义脚本、Google Analytics、图标字体、animate.js 以及我可能需要的任何其他内容?

感谢您的帮助

【问题讨论】:

    标签: javascript reactjs gatsby


    【解决方案1】:

    一种方法(也许是首选方法)是使用 SSR 文件。

    来自docs

    文件 gatsby-ssr.js 允许您更改静态 HTML 文件的内容 因为它们正在被 Gatsby 和 Node.js 进行服务器端渲染 (SSR)。到 使用 Gatsby SSR API,在 您网站的根目录。导出您希望在此使用的任何 API 文件。

    如何做到这一点的教程是here

    它使用setHeadComponents方法注入到html.js中:

    setHeadComponents
    

    它将一个组件数组作为其第一个参数,在构建期间将添加到头组件,并将其传递给 html.js。

    【讨论】:

      【解决方案2】:

      还有另一种方法,就是创建 React 的效果:

      import { useEffect } from 'react'
      
      const useGoogleAnalytics = () => {
      
          useEffect(() => {
              // GA Snippet
          }, [])
      
          return null
      }
      

      然后您可以在要包含的页面组件中使用useGoogleAnalytics()

      这样做的主要优点是:

      • 你得到了代码的翻译
      • 维护更复杂的代码比在模板文字中更容易。

      对于像 Google Analytics 这样的简单脚本,我会选择模板文字,但对于自定义和主题可更改的 sn-p,我更喜欢效果。只要您不滥用这些,它就不会影响性能,也不会产生开销。

      有没有人看到这种其他方法的其他缺点?

      【讨论】:

        【解决方案3】:

        您可以通过多种方式将外部脚本(没有 npm 模块)注入到 gatsby.js 项目中。更喜欢为“web-analytics”脚本使用各自的 gatsby-plugin。

        使用require()

        • 在你的项目中创建一个文件myScript.js并粘贴脚本内容
        • 添加const myExtScript = require('../pathToMyScript/myScript')
          render() 内和return() 之前Pages 文件夹中的statefull 组件,如果您想仅在该页面上执行该脚本( =页面/组件范围)。

          export default class Contact extends React.Component {  
            render() {  
             const myExtScript = require('../pathToMyScript/myScript')  
              return (
                ........       
                         )}
          
        • 如果您想在全局范围(=在每个页面/组件中)执行脚本:
          添加到html.js

          <script dangerouslySetInnerHTML= {{ __html: ` 
              putYourSciptHereInBackticks `}} />`  
          

          在关闭&lt;/body&gt; 之前。最好在这个组件上操作/监控你的全局范围,因为它有这个特定的目的……将 html 注入全局的每个页面/路由。

        • 全局范围注入的另一种方法是在组件声明之前使用require()这会起作用,但这不是一个好习惯,因为您的组件不应该在全局范围内注入任何东西。

           const myExtScript = require('../pathToMyScript/myScript')  
          
             export default class Contact extends React.Component {  
              render() {  
                return (
                ........       
                         )}
          

        附:抱歉,如果没有正确编辑答案。这是我在 StackOverflow 上的第一个答案。

        【讨论】:

        • 你会展示一些关于这些示例的 GitHub 存储库吗?
        • 什么是使用在线脚本而不是本地文件的脚本?例如:
        【解决方案4】:

        使用React-Helmet

        第一个import Helmet from 'react-helmet'

        在您的div 中,您可以这样做

        <Helmet>
        <script type='text/javascript'>
        (function(d, s) {
            var useSSL = 'https:' == document.location.protocol;
            var js, where = d.getElementsByTagName(s)[0],
            js = d.createElement(s);
            js.src = (useSSL ? 'https:' : 'http:') +  '//www.peopleperhour.com/hire/1002307300/1213788.js?width=300&height=135&orientation=vertical&theme=light&rnd='+parseInt(Math.random()*10000, 10);
            try { where.parentNode.insertBefore(js, where); } catch (e) { if (typeof console !== 'undefined' && console.log && e.stack) { console.log(e.stack); } }
        }(document, 'script'));
        </script>
        </Helmet>

        【讨论】:

        • 谢谢,但这会产生与我的初始代码相同的语法错误。无法转译
        • 这并不是真正的问题解决方案,但我发现的一种解决方法是使用 Google 跟踪代码管理器注入自定义脚本。这并不适用于所有场景,但如果您要注入跟踪脚本之类的东西,它会非常有效,并且有助于避免在代码中乱扔非托管脚本。我只是用它在 Gatsby 页面上注入 MailChimp 弹出代码,效果很好。
        • 我们是否必须在整个项目的所有文件中使用它?整个项目中包含的单曲有什么聪明的工作吗?
        • @AaronNewton GTM 不适用于 mailchimp 脚本,对吗?据我所知没有。
        • @Logemann 我最近没有尝试过,但是您可以使用 GTM 将任何脚本注入到页面中。当我陷入困境时,我什至用它来替换内容。 support.google.com/tagmanager/answer/6107167?hl=en
        【解决方案5】:

        显然使用多行 JS 语法可以解决问题,如

        let test = "<script type='text/javascript'>\
        (function(d, s) {\
            var useSSL = 'https:' == document.location.protocol;\
            var js, where = d.getElementsByTagName(s)[0],\
            js = d.createElement(s);\
            js.src = (useSSL ? 'https:' : 'http:') +  '//www.peopleperhour.com/hire/1002307300/1213788.js?width=300&height=135&orientation=vertical&theme=light&rnd='+parseInt(Math.random()*10000, 10);\
            try { where.parentNode.insertBefore(js, where); } catch (e) { if (typeof console !== 'undefined' && console.log && e.stack) { console.log(e.stack); } }\
        }(document, 'script'));\
        </script><div id='pph-hireme'></div>"
        

        或者,你可以这样做

        let test2 = `
        <script type='text/javascript'>
        (function(d, s) {
            var useSSL = 'https:' == document.location.protocol;
            var js, where = d.getElementsByTagName(s)[0],
            js = d.createElement(s);
            js.src = (useSSL ? 'https:' : 'http:') +  '//www.peopleperhour.com/hire/1002307300/1213788.js?width=300&height=135&orientation=vertical&theme=light&rnd='+parseInt(Math.random()*10000, 10);\
            try { where.parentNode.insertBefore(js, where); } catch (e) { if (typeof console !== 'undefined' && console.log && e.stack) { console.log(e.stack); } }\
        }(document, 'script'));
        </script><div id='pph-hireme'></div>
        `
        

        欢迎更多的cmets

        【讨论】:

          猜你喜欢
          • 2019-04-03
          • 2019-03-02
          • 1970-01-01
          • 2022-11-19
          • 1970-01-01
          • 2018-11-26
          • 2022-01-23
          • 2020-11-07
          • 2020-09-11
          相关资源
          最近更新 更多