在 Gatsby React 页面中添加带有 <script> 的原始 HTML

新手上路,请多包涵

我正在尝试将外部嵌入代码添加到我的 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

这充满了语法错误。您能否指出一种更好的方法来将原始片段包含在 React 组件中?

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

感谢您的帮助

原文由 Giannis Dallas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 517
2 个回答

您可以通过多种方式将外部脚本(没有 npm 模块)注入 gatsby.js 项目。更喜欢将各自的 gatsby-plugin 用于“网络分析”脚本。

使用 require()

  • 在你的项目中创建一个文件 myScript.js 并粘贴脚本内容
  • 添加 const myExtScript = require('../pathToMyScript/myScript')

render() 和之前 return() 页面 文件夹中的 状态 组件,如果你 只想在该页面(=页面/组件范围)执行该脚本。

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

  • 如果你想在 全局范围 内执行脚本(=在每个页面/组件中):

添加到 html.js

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

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

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

     export default class Contact extends React.Component {
      render() {
        return (
        ........
                 )}

PS 对不起,如果答案没有正确编辑。这是我在 StackOverflow 的第一个答案。

原文由 AndreasT 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 反应头盔

首先 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>

原文由 Mohit Bajoria 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题