我正在尝试将外部嵌入代码添加到我的 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 许可协议
您可以通过多种方式将外部脚本(没有 npm 模块)注入 gatsby.js 项目。更喜欢将各自的 gatsby-plugin 用于“网络分析”脚本。
使用
require()
:myScript.js
并粘贴脚本内容const myExtScript = require('../pathToMyScript/myScript')
到
render()
和之前return()
页面 文件夹中的 状态 组件,如果你 只想在该页面(=页面/组件范围)执行该脚本。添加到
html.js
在关闭
</body>
之前。最好在这个组件上操作/监控你的全局范围,因为它有这个特定的目的……将 html 注入到全局的每个页面/路由。require()
。 这会起作用,但这不是一个好的做法,因为您的组件不应该在全局范围内注入任何东西。PS 对不起,如果答案没有正确编辑。这是我在 StackOverflow 的第一个答案。