You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 01:03:26