Telegram Mini Apps Navigator 和 react-router-dom 的集成.! ~& I8 @) l# W# G) [) _
5 y3 [% D4 V7 T2 \" w d/ b L安装
4 J- a+ \3 ]. qpnpm :
/ z" b' k9 D: P* K. j# C% v5 D9 b- pnpm i @telegram-apps/react-router-integration
复制代码 npm :
( \: d% O% W3 ?+ c) u5 c) G9 ~. `- npm i @telegram-apps/react-router-integration
复制代码 yarn :
0 K9 X: ^# b' u0 J: ~- yarn add @telegram-apps/react-router-integration
复制代码 使用方法目前,该软件包只提供一个函数,用于创建 react-router-dom 路由器的集成 - useIntegration。 下面是它的使用方法: - import { useIntegration } from '@telegram-apps/react-router-integration';
0 S7 w3 F' F+ l) i; w7 ~ - import { initNavigator } from '@telegram-apps/sdk-react';4 x" e1 t8 ~/ V: o4 N3 W0 j
- import { useEffect, useMemo } from 'react';
& E9 L+ r1 t. |; I - import {& J9 J, n; b" z+ {0 s6 W$ h ~
- Navigate,
/ [; t- x% A2 E7 E# ?! b5 Q - Route,/ N L ]9 O8 ~6 j* w$ z
- Router,
5 A3 y& Q& e) i - Routes,
0 i# `) V+ j. f% u v - } from 'react-router-dom';8 o: C' o6 y) Y
/ R% \* W: T Q( b9 m; k- import { IndexPage } from './IndexPage.js';
2 e) l2 }' ]2 Q - + Y3 r# w* O& }' E# u2 P! Z h3 Q
- function App() {" E# _! w2 m% V k G0 d* M2 l
- // Create a new application navigator and attach it to the browser history, so it could modify9 N, {6 n6 S S" A* m T' T2 U
- // it and listen to its changes.
+ q6 \) f, L% {$ X: A - const navigator = useMemo(() => initNavigator('app-navigation-state'), []);
, C1 g7 d6 J1 o$ `4 x - const [location, reactNavigator] = useIntegration(navigator);6 g: p6 [& y& B7 W, C
- / Y8 q6 n# ?. I+ x6 y$ B+ T- Z
- // Don't forget to attach the navigator to allow it to control the BackButton state as well
, D1 u* g( Y5 H7 o* S3 H - // as browser history.
w3 g; d5 g9 U" E - useEffect(() => {
+ R6 S5 K4 e( R- ^& H! { - navigator.attach();8 f) V1 J& U$ E R
- return () => navigator.detach();9 K8 ~* V- ~; o) f" G
- }, [navigator]);
) n1 J: J0 T7 @& ?& x - 6 D* s% _( G' `
- return (
8 b% g( \/ n' _$ ]9 t% |, g$ L - <Router location={location} navigator={reactNavigator}>9 s% d- o: \' j( }) H) N
- <Routes>/ R/ r/ l% R8 a
- <Route path={'/'} component={IndexPage}/>! W% R+ S6 m3 z$ ]
- <Route path={'*'} element={<Navigate href={'/'}/>}/>
% _! H* y5 {+ C6 \ - </Routes>" J& L+ a+ J* X4 ]5 o
- </Router>
& f; x0 l/ {$ y7 A ], {; K - );2 V% I# d& d a+ N" _2 |2 Y; ]" J
- }
复制代码您可以通过 我们的 React 模板 了解更多关于如何使用它的实际应用。 / K; ~6 M7 e6 @- u! ~& j
/ R& s1 Z- _) P0 i" h
+ ?; b4 G) J, y# n3 N( ?8 Q2 t. t( I
' M* }, R! @ J
& D# Z6 G8 B# X6 P3 K' A2 x+ } |