Telegram Mini Apps Navigator 和 react-router-dom 的集成.0 t8 _. x$ ]& i3 {
8 g; {' X- e1 {" j安装9 I. }, y" b8 L
pnpm :
2 F% y# C# k' e- pnpm i @telegram-apps/react-router-integration
复制代码 npm :! q5 ]7 d- t. K' q8 V- z6 ]
- npm i @telegram-apps/react-router-integration
复制代码 yarn :. r/ V$ V( l! e* h
- yarn add @telegram-apps/react-router-integration
复制代码 使用方法目前,该软件包只提供一个函数,用于创建 react-router-dom 路由器的集成 - useIntegration。 下面是它的使用方法: - import { useIntegration } from '@telegram-apps/react-router-integration';' d q+ a; t( U9 X6 I2 c4 p
- import { initNavigator } from '@telegram-apps/sdk-react';
% _4 J! ?+ X9 H7 }$ ^ - import { useEffect, useMemo } from 'react';* D3 E; K5 T: Y
- import {; d2 w' H2 P8 q* r) ^( h" B* X6 Y
- Navigate,6 c) s3 m1 V2 N- a5 C4 a+ [
- Route,+ `3 V8 X" E, f/ j5 c* M2 `: v7 Q
- Router, ?% P# k1 Q- w
- Routes,
. r {, z$ h8 g/ s2 l6 d4 w9 n' g - } from 'react-router-dom';2 t& I) P3 C3 W
- * z, S! H, [* [% `7 D5 h5 f# c
- import { IndexPage } from './IndexPage.js';4 B9 Q9 G0 C: ?6 d+ J
- & ]3 s+ V$ B) O
- function App() {
2 N% G3 V( M; J- H, Q1 a% Z7 l. U - // Create a new application navigator and attach it to the browser history, so it could modify
. ?9 E% y2 B. ? - // it and listen to its changes.
# o6 t. d) p4 ?1 L$ u; O, h' R - const navigator = useMemo(() => initNavigator('app-navigation-state'), []);
0 Y$ I F9 W! x: s- D2 ] - const [location, reactNavigator] = useIntegration(navigator);$ e% `3 r1 @, K$ _+ M4 i3 A0 T
- $ a5 _/ A2 l8 x, v0 \. ?
- // Don't forget to attach the navigator to allow it to control the BackButton state as well
) l, z$ I( l! ?: s( { - // as browser history.
" @% r" e8 J) k! T - useEffect(() => {
% N7 S, a, p- \" U- ]& b# M - navigator.attach();% ?& x+ s' F( `+ v# c3 W: r4 s# Q
- return () => navigator.detach();: l7 O/ o, p& {- w
- }, [navigator]);) q$ `# L) o; \7 j: L
+ u" q0 G) R9 Q$ i H- return (
9 X! \3 j2 v o7 t9 m/ J& U" @ - <Router location={location} navigator={reactNavigator}>4 ]+ U* d- _. G7 y7 l
- <Routes>& }' @5 W# m7 | ?, z
- <Route path={'/'} component={IndexPage}/>
6 D1 e0 X/ M. C6 S& W$ i& u - <Route path={'*'} element={<Navigate href={'/'}/>}/>9 \7 V( A0 ]6 A) N5 Z
- </Routes>8 F4 _4 n" u" m* b I4 ^
- </Router>
d1 O6 x8 [6 N' p: G5 J - );
( Y: W p' g) b$ w9 r3 P1 a - }
复制代码您可以通过 我们的 React 模板 了解更多关于如何使用它的实际应用。
& A8 E5 Y" v8 q3 v. J. A; F. W8 R) E8 a5 g
) L" W# y2 |* X" |1 Q( l) v& Z& R* I8 r# L% G' O" ?
; e0 @( [" ^' N' l2 s( d |