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

如何解决Vite+React开发的Telegram Mini App触屏设备异常滚动折叠问题?

解决Telegram Mini App触屏设备意外滚动与折叠问题

先修正API初始化的错误写法

你当前的script标签写法存在问题:带src属性的script标签内部代码不会被执行,必须将API初始化逻辑单独放在另一个script标签中:

<script src="https://telegram.org/js/telegram-web-app.js"></script>
<script>
  window.Telegram.WebApp.ready();
  window.Telegram.WebApp.expand();
  window.Telegram.WebApp.disableVerticalSwipes();
  // 额外禁用下拉刷新(部分场景下会触发)
  if (window.Telegram.WebApp.disablePullToRefresh) {
    window.Telegram.WebApp.disablePullToRefresh();
  }
</script>

全局CSS层面封锁默认滚动行为

在全局样式文件(如index.css)中添加以下规则,从根源禁止页面的默认滚动和触摸触发的滚动行为:

html, body {
  overflow: hidden !important;
  height: 100% !important;
  touch-action: none !important;
}

/* 若App内有需要自定义滚动的区域,单独给该区域恢复滚动权限 */
.custom-scroll-container {
  touch-action: pan-y !important;
  overflow-y: auto !important;
}

React组件内拦截异常触摸事件

在根组件(如App.jsx)中添加触摸事件监听,精准阻止非预期的滚动触发:

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    const blockUnwantedScroll = (e) => {
      // 仅当触摸目标不在自定义滚动区域内时,阻止默认行为
      if (!e.target.closest('.custom-scroll-container')) {
        e.preventDefault();
      }
    };

    window.addEventListener('touchmove', blockUnwantedScroll, { passive: false });
    return () => {
      window.removeEventListener('touchmove', blockUnwantedScroll);
    };
  }, []);

  // ... 组件其他业务代码
}

export default App;

确保App始终保持展开状态

监听Telegram WebApp的视口变化事件,在必要时重新调用展开方法,防止App被意外折叠:

useEffect(() => {
  const keepAppExpanded = () => {
    window.Telegram.WebApp.expand();
  };

  window.Telegram.WebApp.onEvent('viewportChanged', keepAppExpanded);
  return () => {
    window.Telegram.WebApp.offEvent('viewportChanged', keepAppExpanded);
  };
}, []);

额外注意事项

  • 避免依赖浏览器原生滚动逻辑,若需滚动区域,使用自定义滚动库(如react-custom-scrollbars)完全控制滚动行为。
  • 测试时覆盖iOS、Android不同系统的Telegram客户端,确保跨设备兼容性。

内容的提问来源于stack exchange,提问作者someone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:05:01