Telegram Mini Apps Navigator 和 react-router-dom 的集成.
' k1 _) A' R7 j" S. D" g" e( f
2 _, t5 p- l. Y6 ]0 S( o G5 V安装; p; v* R1 z- C
pnpm :
! z. ?$ | ]* ]# P; @4 y- pnpm i @telegram-apps/react-router-integration
复制代码 npm :. c. }0 A+ O6 _) a. I" E
- npm i @telegram-apps/react-router-integration
复制代码 yarn :, p) k, m% w2 |# x2 d [# ]
- yarn add @telegram-apps/react-router-integration
复制代码 使用方法目前,该软件包只提供一个函数,用于创建 react-router-dom 路由器的集成 - useIntegration。 下面是它的使用方法: - import { useIntegration } from '@telegram-apps/react-router-integration';7 q2 ? o4 t6 R2 H* D
- import { initNavigator } from '@telegram-apps/sdk-react';
2 H# g0 r" Y W) j! B. U - import { useEffect, useMemo } from 'react';
& z) W+ i' X6 J8 `3 z" B) i3 b6 M - import {: G9 R- h) ?1 y2 E& H3 m
- Navigate,
. m' v ]# Z) c+ z- H0 v9 i& ` - Route,
& E# K# i& X/ L# f: w" Y3 t - Router,6 Q1 V- r$ Q) Q7 Y- ]4 q
- Routes, q' J i5 }( F) U. b) r
- } from 'react-router-dom';4 N2 \9 r* A3 o% R2 _
- 6 M+ O! r' s$ n2 Y
- import { IndexPage } from './IndexPage.js';$ {. _* b$ |* d. W& W7 x& P
3 Y) T8 k: l+ H6 N3 j' m; H- function App() {
% b7 w- C* Z- g5 l - // Create a new application navigator and attach it to the browser history, so it could modify7 m1 L) G2 R$ a6 h% R- e: m
- // it and listen to its changes.
8 B+ e' R: I5 e9 P: d$ { - const navigator = useMemo(() => initNavigator('app-navigation-state'), []);
$ o9 L/ R: z. \ T; }. ?: w% w U - const [location, reactNavigator] = useIntegration(navigator);0 C( r: Z$ m3 d# u9 I1 G* H
2 \6 `4 P, [2 a6 r8 u- // Don't forget to attach the navigator to allow it to control the BackButton state as well) n9 }1 a0 i( j+ s6 ^* V' s: u
- // as browser history.5 I- m4 k6 s0 y
- useEffect(() => {% T/ N' H9 \' ^$ b, I; t- H- ~
- navigator.attach();/ X) l1 Q& ^8 M0 L, B
- return () => navigator.detach();
- ^5 g' c; x7 ^, P4 Z; g3 j - }, [navigator]);9 C# q3 `( M5 R
! Z! _. q2 J v. S+ P9 \- return (
8 b/ }4 }/ u" a- u - <Router location={location} navigator={reactNavigator}>
% P" m! v: V6 q) g5 T - <Routes>3 J# q, H( N. j5 _9 L# e4 x
- <Route path={'/'} component={IndexPage}/>
! d$ j* }& W4 r% W# h2 Y - <Route path={'*'} element={<Navigate href={'/'}/>}/>
/ r7 F: f, p0 H - </Routes>
5 @; ~, n' R @1 H8 G - </Router>
7 n6 c4 ]) Q1 J/ @$ I, }$ } - );' k: ?1 O" Z$ u. A
- }
复制代码您可以通过 我们的 React 模板 了解更多关于如何使用它的实际应用。
# n" A9 s" k* I- n% b4 C: p: q: q& D& w' y* X
- u/ {+ t! t1 O; ?7 r; i, C6 L3 x. j1 I: A, s
, N6 O+ c( p* V$ M& G: T |