在Next.js中点击按钮动态加载Disqus评论
实现点击加载Disqus评论(React 18.2 + Next.js 13)
方案一:基于disqus-react的动态加载实现
利用Next.js的dynamic导入功能,将Disqus组件设置为仅客户端加载,再通过状态控制是否渲染组件,实现点击按钮加载评论的效果:
import { useState } from 'react'; import dynamic from 'next/dynamic'; // 动态导入DiscussionEmbed,禁用SSR const DynamicDiscussionEmbed = dynamic( () => import('disqus-react').then(mod => mod.DiscussionEmbed), { ssr: false, loading: () => <p>加载评论中...</p> } ); export async function getStaticProps() { return { props: { ...posts.find(post => post.slug == 'my-best-post') } } } export default function Post(props) { const [showComments, setShowComments] = useState(false); return <> Post text.... {!showComments ? ( <button onClick={() => setShowComments(true)}>加载评论</button> ) : ( <DynamicDiscussionEmbed shortname='myid' config={{ // 填入你的配置参数 url: props.url, identifier: props.id, title: props.title }} /> )} </> }
方案二:原生加载Disqus脚本(无需disqus-react)
如果不想依赖第三方包,可以直接通过动态插入脚本的方式实现:
import { useState, useEffect } from 'react'; export async function getStaticProps() { return { props: { ...posts.find(post => post.slug == 'my-best-post') } } } export default function Post(props) { const [showComments, setShowComments] = useState(false); useEffect(() => { if (showComments) { // 配置Disqus参数 window.disqus_config = function () { this.page.url = props.url; this.page.identifier = props.id; this.page.title = props.title; }; // 创建并插入Disqus脚本 const script = document.createElement('script'); script.src = 'https://myid.disqus.com/embed.js'; script.setAttribute('data-timestamp', Date.now().toString()); script.async = true; document.body.appendChild(script); // 组件卸载时清理脚本 return () => { document.body.removeChild(script); delete window.disqus_config; delete window.DISQUS; }; } }, [showComments, props]); return <> Post text.... {!showComments ? ( <button onClick={() => setShowComments(true)}>加载评论</button> ) : ( <div id="disqus_thread"></div> )} </> }
关于动态导入的SSR选项疑问
因为Disqus评论完全是客户端交互内容,不需要在服务器端渲染,所以只需要设置ssr: false就足够了。这个选项会让Next.js不在服务端渲染该组件,仅在客户端加载,避免服务端加载不必要的Disqus资源,完全匹配你的性能优化需求。不需要额外添加其他针对外部库的选项,ssr: false已经覆盖了核心需求。
内容的提问来源于stack exchange,提问作者Sergey Sypalo
相关产品推荐
相关产品推荐

