【发布时间】:2020-12-01 14:28:36
【问题描述】:
我正在尝试为我的 Gatsby 网站创建一个 Buy Me A Coffee React 组件,即使我的 Gatsby 网站在开发模式下运行并成功构建,该组件(Buy Me A Coffee 小部件)在加载页面。
我的网站使用 MDX,所以理想情况下我希望能够将组件导入到我的博客文章中。我喜欢将它导入我的博客文章的想法,因为它允许我有选择地包含它,而如果我使用像 gatsby-ssr.js 这样的标准解决方案来包含第三方 Buy Me A Coffee 脚本,我预见它会更多很难规范组件在哪些页面上显示和不显示。
目前,我使用库 browser-monads,因此我不必为构建我的网站执行typeof !== "undefined" 条件检查。使用他们在这里推荐的传统条件格式并没有帮助。此外,styles.scss 目前是空的。我正在导入它,以防以后需要返回并为我的组件添加样式。
感谢您的帮助!
下面是我的代码:
import React from 'react';
import './styles.scss'
import { window, document, exists } from 'browser-monads';
class BuyMeACoffee extends React.Component {
constructor(props){
super(props)
let script = document.createElement("script");
script.setAttribute('data-name','BMC-Widget')
script.src = "https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js"
script.setAttribute('data-id', 'x');
script.setAttribute('data-description', 'Thank you for your support!');
script.setAttribute('data-message', "We're proudly reader-supported! If our content helps you, we would be honored and greatly appreciate it if you'd consider buying us a coffee!");
script.setAttribute('data-color',"#2962ff")
script.setAttribute('data-position','right')
script.setAttribute('data-x_margin','18')
script.setAttribute('data-y-margin','18')
script.async = true
//Call window on load to show the image
script.onload=function(){
var evt = document.createEvent('Event');
evt.initEvent('load', false, false);
window.dispatchEvent(evt);
}
this.script=script
}
componentDidMount () {
document.head.appendChild(this.script)
}
componentWillUnmount(){
document.head.removeChild(this.script);
document.body.removeChild(document.getElementById("bmc-wbtn"))
}
render(){
return(null)
}
}
export default LoadBuyMeACoffee;
【问题讨论】:
-
我注意到我忘记更新我的导出名称
export default LoadBuyMeACoffee;将其更新为export default BuyMeACoffee;没有帮助。
标签: javascript reactjs gatsby