我正在尝试创建一个useDisqus
钩子,看起来像:
import React from 'react'
import { siteMetadata } from '@/_data/index'
const config = siteMetadata.comment.disqus
const SHORTNAME = config.shortname as string
export const useDisqus = (commentNodeId: string, slug: string) => {
React.useEffect(() => {
const scriptParentNode = document.getElementById(commentNodeId)
if (!scriptParentNode) return
;(window as any).disqus_config.page.url = window.location.href
;(window as any).disqus_config.page.identifier = slug // how to write this??
if ((window as any).DISQUS === undefined) {
const script = document.createElement('script')
const attributes = {
src: `https://${SHORTNAME}disqus.com/embed.js`,
'data-timestamp': `${+new Date()}`,
crossorigin: 'anonymous',
async: 'true',
}
Object.entries(attributes).forEach(([name, value]) => script.setAttribute(name, value))
scriptParentNode.appendChild(script)
} else {
;(window as any).DISQUS.reset({ reload: true })
}
}, [commentNodeId, slug])
}
我从另一个存储库中得到的带有Load Comments
按钮的完整工作组件看起来像:
import React, { useState } from 'react'
import siteMetadata from '@/data/siteMetadata'
const Disqus = ({ frontMatter }) => {
const [enableLoadComments, setEnabledLoadComments] = useState(true)
const COMMENTS_ID = 'disqus_thread'
function LoadComments() {
setEnabledLoadComments(false)
window.disqus_config = function () {
this.page.url = window.location.href
this.page.identifier = frontMatter.slug
}
if (window.DISQUS === undefined) {
const script = document.createElement('script')
script.src = 'https://' + siteMetadata.comment.disqus.shortname + '.disqus.com/embed.js'
script.setAttribute('data-timestamp', +new Date())
script.setAttribute('crossorigin', 'anonymous')
script.async = true
document.body.appendChild(script)
} else {
window.DISQUS.reset({ reload: true })
}
}
return (
<div className="pt-6 pb-6 text-center text-gray-700 dark:text-gray-300">
{enableLoadComments && <button onClick={LoadComments}>Load Comments</button>}
<div className="disqus-frame" id={COMMENTS_ID} />
</div>
)
}
export default Disqus
注意,此部分:
window.disqus_config = function () {
this.page.url = window.location.href
this.page.identifier = frontMatter.slug
}
Idk如何将其转换为useDisqus
钩子,因为this.
是无状态组件中的undefined
。
如何转换该部分?我目前已经把它写如下,但它不起作用:
;(window as any).disqus_config.page.url = window.location.href
;(window as any).disqus_config.page.identifier = slug // how to write this??
快速查看文档,window.disqus_config
似乎是一个设置一些变量的函数。函数主体内的this
指的是函数本身的this
上下文,而不是组件。
作为TypeScript问题,您可以为函数声明this
类型。您知道它应该是带有page
对象的东西。试试这个:
;(window as any).disqus_config = function(this: {page: Record<string, string>}) {
this.page.url = window.location.href
this.page.identifier = slug
}