React中Twitter Timeline Widget的data-tweet-limit属性失效问题
问题解决:Twitter Timeline Widget 的推文数量限制失效
问题根源
Twitter 官方已废弃原有的 data-tweet-limit 属性,原自动渲染的 <a class="twitter-timeline"> 方式不再支持该参数,导致你的设置无法生效。目前必须通过 Twitter Widgets JS API 主动创建时间线,才能配置推文数量限制。
修复方案
改用 twttr.widgets.createTimeline 方法初始化时间线,通过 maxItems 参数指定显示的推文数量,同时优化 React 组件的渲染逻辑避免重复加载与内存泄漏:
import { useEffect, useRef } from 'react'; function TwitterWidget(props: Props) { const { profileName } = props; const twitterEmbedRef = useRef<HTMLDivElement>(null); useEffect(() => { if (!twitterEmbedRef.current || !profileName) return; // 清空容器,避免重复渲染 twitterEmbedRef.current.innerHTML = ''; // 处理 widgets.js 加载逻辑(确保只加载一次) const initTimeline = () => { window.twttr.widgets.createTimeline( { sourceType: 'profile', screenName: profileName, maxItems: 2 // 控制显示的推文数量 }, twitterEmbedRef.current, { // 可选配置:主题、宽度等 theme: 'light' } ); }; if (!window.twttr) { const script = document.createElement('script'); script.src = 'https://platform.twitter.com/widgets.js'; script.async = true; script.onload = initTimeline; document.body.appendChild(script); } else { initTimeline(); } // 组件卸载/更新时清理资源 return () => { if (window.twttr && twitterEmbedRef.current) { window.twttr.widgets.disconnect(twitterEmbedRef.current); } }; }, [profileName]); return ( <WidgetWrapper> <section className='twitterContainer'> <div className='twitter-embed' ref={twitterEmbedRef}></div> </section> </WidgetWrapper> ); };
关键说明
- 使用
useRef获取容器 DOM 节点,便于 JS API 直接操作 - 检查
window.twttr全局对象,避免重复加载widgets.js - 通过
maxItems参数(官方当前支持的参数)设置推文数量限制 - 添加清理函数,在组件卸载或
profileName变化时断开时间线连接,防止内存泄漏 - 将
profileName加入 useEffect 依赖数组,确保切换账号时重新生成时间线
内容的提问来源于stack exchange,提问作者Shamil Maashev
相关产品推荐
相关产品推荐

