安裝 react-router-dom 目前最新版本6.8.1
1 npm install react-router-dom
src/index.js加入 import { BrowserRouter } from ‘react-router-dom’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { BrowserRouter } from 'react-router-dom' const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <BrowserRouter> <App /> </BrowserRouter> ); reportWebVitals();
pages資料內新增兩個檔案 FirstPage.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import React from 'react'; const FirstPage=()=>{ const StyleSheet={ width:"100vw", height:"100vh", backgroundColor:"#FF2E63", display: "flex", alignItems:"center", justifyContent:"center", flexDirection:"column" } return( <div style={StyleSheet}> <h1 style={{color:"white",fontFamily:"Microsoft JhengHei"}}>我是第一頁</h1> </div> ) } export default FirstPage;
SecondPage.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import React from 'react'; const SecondPage=()=>{ const StyleSheet={ width:"100vw", height:"100vh", backgroundColor:"#08D9D6", display: "flex", alignItems:"center", justifyContent:"center", flexDirection:"column" } return( <div style={StyleSheet}> <h1 style={{color:"white",fontFamily:"Microsoft JhengHei"}}>我是第二頁</h1> </div> ) } export default SecondPage;
App.js檔案如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import { Routes,Route,} from 'react-router-dom' import './App.css'; import FirstPage from "./pages/FirstPage"; import SecondPage from "./pages/SecondPage"; function App() { return ( <div className="App"> <h1>Home</h1> <ul> <li><a href='/'>Home</a></li> <li><a href='/secondpage'>SecondPage</a></li> </ul> <Routes> <Route index element={<FirstPage />} /> <Route path='secondpage' element={<SecondPage />} /> </Routes> </div> ); } export default App;