1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import React from 'react' import ReactDOM from 'react-dom/client' import './index.css'
import { BrowserRouter as Router, Routes, Route, useNavigate, Link } from 'react-router-dom'
const Login = () => { const navigate = useNavigate() const handleLogin = () => { navigate('/home') }
return ( <div> <p>登录页面</p> <button onClick={handleLogin}>登录</button> </div> ) }
const Home = (props) => { const navigate = useNavigate() const handleBack = () => { navigate(-1) } return ( <div> <h2>我是后台首页</h2> <button onClick={handleBack}>返回登录页面按钮</button> </div> ) }
const App = () => ( <Router> <div> <h1>编程式导航:</h1> <Link to="/login">去登录页面</Link> <Routes> <Route path="/login" element={<Login></Login>} /> <Route path="/home" element={<Home></Home>} /> </Routes> </div> </Router> )
const root = ReactDOM.createRoot(document.getElementById('root')) root.render(<App />)
|