TelegramBackButton
控制 Telegram 顶部导航栏的返回按钮。这是一个无渲染组件,通过 Telegram WebApp API 控制原生返回按钮。
导入
tsx
import { TelegramBackButton } from '@xcloud/ui-telegram'示例
基础使用
最简单的使用方式,点击返回按钮触发回调:
tsx
import { TelegramBackButton } from '@xcloud/ui-telegram'
function DetailPage() {
const handleBack = () => {
console.log('Back button clicked')
// 执行返回逻辑
}
return (
<>
<TelegramBackButton onClick={handleBack} />
<div>Page content...</div>
</>
)
}与路由集成
配合 React Router 使用:
tsx
import { TelegramBackButton } from '@xcloud/ui-telegram'
import { useNavigate } from 'react-router-dom'
function ProfilePage() {
const navigate = useNavigate()
return (
<>
<TelegramBackButton onClick={() => navigate(-1)} />
<div>Profile content...</div>
</>
)
}条件显示
根据页面状态控制返回按钮的显示:
tsx
import { TelegramBackButton } from '@xcloud/ui-telegram'
import { useState } from 'react'
function EditPage() {
const [showBackButton, setShowBackButton] = useState(true)
return (
<>
<TelegramBackButton
visible={showBackButton}
onClick={() => navigate(-1)}
/>
<button onClick={() => setShowBackButton(!showBackButton)}>
Toggle Back Button
</button>
</>
)
}确认对话框
在返回前显示确认对话框:
tsx
import { TelegramBackButton } from '@xcloud/ui-telegram'
import { useState } from 'react'
function FormPage() {
const [isDirty, setIsDirty] = useState(false)
const navigate = useNavigate()
const handleBack = () => {
if (isDirty) {
if (confirm('You have unsaved changes. Are you sure you want to leave?')) {
navigate(-1)
}
} else {
navigate(-1)
}
}
return (
<>
<TelegramBackButton onClick={handleBack} />
<form onChange={() => setIsDirty(true)}>
{/* Form fields */}
</form>
</>
)
}组件 API
TelegramBackButton Props
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
onClick | () => void | - | 点击返回按钮的回调函数 |
visible | boolean | true | 是否显示返回按钮 |
行为说明
- 无渲染: 组件本身不渲染任何 DOM 元素,返回
null - 原生控制: 通过 Telegram WebApp API 的
backButton对象控制原生返回按钮 - 自动挂载: 组件挂载时自动初始化返回按钮
- 自动清理: 组件卸载时自动隐藏返回按钮
- 状态同步:
visible属性变化时实时更新按钮显示状态 - 事件绑定:
onClick回调变化时自动更新事件监听器
注意事项
- 必须在 TelegramProvider 中使用: 确保应用被 TelegramProvider 包裹
- 只在 Telegram 环境有效: 在非 Telegram 环境中组件不会有任何效果
- 避免多次使用: 同一时间只应该有一个 TelegramBackButton 组件
- 自动清理: 组件卸载时会自动隐藏返回按钮,无需手动清理
最佳实践
路由级别使用
建议在路由级别使用返回按钮,而不是在具体组件中:
tsx
// routes/profile.tsx
import { TelegramBackButton } from '@xcloud/ui-telegram'
export function ProfileRoute() {
const navigate = useNavigate()
return (
<>
<TelegramBackButton onClick={() => navigate(-1)} />
<ProfilePage />
</>
)
}配合 Layout 使用
可以在 Layout 组件中统一管理:
tsx
import { TelegramBackButton } from '@xcloud/ui-telegram'
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
function AppLayout() {
const navigate = useNavigate()
const location = useLocation()
// 首页不显示返回按钮
const showBackButton = location.pathname !== '/'
return (
<>
{showBackButton && (
<TelegramBackButton onClick={() => navigate(-1)} />
)}
<Outlet />
</>
)
}相关链接
- TelegramProvider - Telegram 环境提供者
- TelegramMainButton - 主按钮组件
- @tma.js/sdk backButton API