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

标签 javascript reactjs gatsby

我正在尝试将外部嵌入代码添加到我的 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 以及我可能需要的任何其他内容?

谢谢你的帮助

最佳答案

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

使用 require() :

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

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

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

    在关闭 </body> 之前.最好在此组件上操纵/监视您的全局范围,因为它具有特定目的...将 html 注入(inject)全局的每个页面/路由。

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

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

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

关于javascript - 在 Gatsby React 页面中添加带有 &lt;script&gt; 的原始 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48966464/

相关文章:

javascript - 将菜单导航链接到两个不同选项卡中具有相同 ID 的两个 div

javascript - 丑化 css 类名,如 instagram 或 facebook

javascript - 如何更改查询值(其中 : { }) with Apollo GraphQL

javascript - 跟踪多个文本输入的值以确认它们在 JavaScript/React 文字游戏中都是正确的最佳方法

javascript - 我如何异步拦截点击

reactjs - 将 gatsby-plugin-material-ui 与 gatsby 一起使用时,将主题文件放在哪里?

javascript - 将字符串解析为 DOM

java - 使用 facebooklogin 插件的网站并将用户凭据存储到数据库 JAVA 或 Javascript 到我表单的文本框中

Gatsby 内容搜索

npm - VSCode 调试和 Jest : No breakpoints running with npm, 使用节点运行时出现 CWD 错误