React routerato standardowa biblioteka do routingu w React. Umożliwia nawigację między widokami różnych komponentów w aplikacji React, umożliwia zmianę adresu URL przeglądarki i utrzymuje synchronizację interfejsu użytkownika z adresem URL.
Stwórzmy prostą aplikację do Reacta, aby zrozumieć, jak działa React Router. Aplikacja będzie zawierała trzy komponenty: komponent domowy, komponent o komponencie oraz komponent kontaktowy. Do poruszania się między tymi komponentami użyjemy React Router.
Konfigurowanie aplikacji React:Stwórz aplikację React używająctwórz-reaguj-aplikacjęi nazwijmy tomaniacy.
Notatka:Jeśli wcześniej instalowałeś globalnie aplikację create-react-app przez npm, bezpośrednio użyj poniższego polecenia:
npx maniacy tworzenia-reagowania-aplikacji
Twoje środowisko programistyczne jest gotowe. Zainstalujmy teraz React Router w naszej aplikacji.
Instalacja React Routera:React Router można zainstalować przeznpw Twojej aplikacji React. Wykonaj poniższe czynności, aby zainstalować Router w swojej aplikacji React:
- Krok 1: płyta CDdo katalogu projektu, tjmaniacy.
- Krok 2:Aby zainstalować React Router, użyj następującego polecenia:
npm install – -save react-router-dom lub npm i react-router-dom
(to zaktualizowane polecenie)
Po zainstalowaniu react-router-dom dodaj jego komponenty do swojej aplikacji React.
Dodawanie komponentów routera React:Główne komponenty React Routera to:
- PrzeglądarkaRouter:BrowserRouter to implementacja routera, która wykorzystuje interfejs API historii HTML5 (pushState, replaceState i zdarzenie popstate), aby zapewnić synchronizację interfejsu użytkownika z adresem URL. Jest to komponent nadrzędny, który jest używany do przechowywania wszystkich pozostałych komponentów.
- Trasy:Jest to nowy komponent wprowadzony w v6 i uaktualnienie
część. Główne zalety Routes Over Switch to: - Względny
s i s - Trasy są wybierane na podstawie najlepszego dopasowania, a nie pokonywane w kolejności.
- Względny
- Trasa:Trasa to warunkowo wyświetlany komponent, który renderuje interfejs użytkownika, gdy jego ścieżka jest zgodna z bieżącym adresem URL.
- Połączyć:Komponent Link służy do tworzenia linków do różnych tras i implementacji nawigacji po aplikacji. Działa jak HTMLznacznik kotwicy.
Aby dodać komponenty React Router do swojej aplikacji, otwórz katalog projektu w edytorze, którego używasz i przejdź do niegoaplikacja.jsplik. Teraz dodaj poniższy kod w pliku app.js.
import {
BrowserRouter jako Router,
Trasy,
Trasa,
Połączyć
} z
„React-router-dom”
;
Notatka:BrowserRouter jest aliasem Routera.
Korzystanie z routera reagowania:Aby użyć React Router, najpierw utwórzmy kilka komponentów w aplikacji React. W katalogu projektu utwórz folder o nazwieczęśćwewnątrz folderu src, a teraz dodaj 3 pliki o nazwiestrona główna.js,o.jsIkontakt.jsdo folderu komponentu.
Dodajmy trochę kodu do naszych 3 komponentów:
- Strona główna.js:
importuj Reaguj z
'reagować'
;
funkcjonować
Dom (){
powrót
Witamy w świecie maniaków!
}
eksport
domyślny
Dom;
- About.js:
importuj Reaguj z
'reagować'
;
funkcjonować
O () {
powrót
GeeksforGeeks to portal informatyczny
Do
maniacy!
Przeczytaj więcej o nas na:
https:
//www.geeksforgeeks.org/about/
}
eksport
domyślny
O;
importuj Reaguj z
'reagować'
;
funkcjonować
Kontakt (){
powrót
Znajdziesz nas tutaj:
GeeksforGeeks
5. i 6. piętro, Royal Kapsons, A-118,
Sector- 136, Noida, Uttar Pradesh (201305)
}
eksport
domyślny
Kontakt;
Teraz dołączmy do aplikacji komponenty React Router:
- PrzeglądarkaRouter:Dodaj BrowserRouter aliasowany jako Router do pliku app.js, aby opakować wszystkie pozostałe komponenty. BrowserRouter jest komponentem nadrzędnym i może mieć tylko jedno dziecko.
klasa Aplikacja rozszerza komponent {
renderowanie() {
powrót
(
„Aplikacja”
>
);
}
}
- Połączyć:Utwórzmy teraz linki do naszych komponentów. Komponent łącza używaDoprop, aby opisać lokalizację, do której powinny prowadzić linki.
„Aplikacja”
>
"/"
>Strona główna
"/o"
>O nas
"/kontakt"
>Skontaktuj się z nami
Teraz uruchom aplikację na lokalnym hoście i kliknij utworzone łącza. Zauważysz, że adres URL zmienia się zgodnie z wartością wDorekwizyty komponentu Link.
- Trasa:Komponent trasy pomoże nam teraz ustalić powiązanie między interfejsem użytkownika komponentu a adresem URL. Aby uwzględnić trasy do aplikacji, dodaj poniższy kod do pliku app.js.
'/'
element={< Strona główna />}>
'/o'
element={< Informacje />}>
'/kontakt'
element={< Kontakt />}>
Komponenty są teraz połączone, a kliknięcie dowolnego łącza spowoduje wyświetlenie skojarzonego z nim komponentu.
Spróbujmy teraz zrozumieć rekwizyty związane z komponentem Trasa.- 1. dokładnie:Służy do dopasowania dokładnej wartości do adresu URL. Na przykład dokładna ścieżka = „/about” wyrenderuje komponent tylko wtedy, gdy dokładnie pasuje do ścieżki, ale jeśli usuniemy dokładne ze składni, interfejs użytkownika będzie nadal renderowany, nawet jeśli struktura będzie podobna do /about/10.
- 2. ścieżka:Ścieżka określa nazwę ścieżki, którą przypisujemy do naszego komponentu.
- 3. pierwiastek:Odnosi się do komponentu, który będzie renderowany po dopasowaniu ścieżki.
Notatka:Domyślnie trasy są włączane, co oznacza, że więcej niż jeden komponent Route może pasować do ścieżki URL i renderować w tym samym czasie. Jeśli chcemy wyrenderować pojedynczy komponent, musimy użyćtrasy.
- 1. dokładnie:Służy do dopasowania dokładnej wartości do adresu URL. Na przykład dokładna ścieżka = „/about” wyrenderuje komponent tylko wtedy, gdy dokładnie pasuje do ścieżki, ale jeśli usuniemy dokładne ze składni, interfejs użytkownika będzie nadal renderowany, nawet jeśli struktura będzie podobna do /about/10.
- Trasy:Aby wyrenderować pojedynczy komponent, zawiń wszystkie trasy w komponencie Routes.
'/'
element={< Strona główna />}>
'/o'
element={< Informacje />}>
'/kontakt'
element={< Kontakt />}>
Przełącz grupowanie kilku tras, iteruj po nich i znajdź pierwszą, która pasuje do ścieżki. W ten sposób renderowany jest odpowiedni komponent ścieżki.
Po dodaniu wszystkich komponentów oto nasz kompletny kod źródłowy:
importuj React, { Komponent } z
'reagować'
;
importuj {BrowserRouter jako Router, Trasy, Trasa, Łącze} z
„React-router-dom”
;
importuj dom z
„./komponent/strona główna”
;
importuj informacje z
„./komponent/informacje”
;
importuj kontakt z
„./komponent/kontakt”
;
import
'./App.css'
;
klasa Aplikacja rozszerza komponent {
renderowanie() {
powrót
(
„Aplikacja”
>
„Nagłówek aplikacji”
>
"/"
>Strona główna
"/o"
>O nas
"/kontakt"
>Skontaktuj się z nami
'/'
element={< Strona główna />}>
'/o'
element={< Informacje />}>
'/kontakt'
element={< Kontakt />}>
);
}
}
eksport
domyślny
Aplikacja;
Teraz możesz kliknąć linki i przejść do różnych komponentów. React Router zapewnia synchronizację interfejsu użytkownika aplikacji z adresem URL.
Wreszcie udało nam się zaimplementować nawigację w naszej aplikacji React za pomocą React Router.
Ostatnio zaktualizowany :10 maja 2023 r
Jak artykuł
Zapisz artykuł