React中跳转页面并传递参数可以使用React Router。以下是基本示例:
- 在主页中定义路由:
import { Route, BrowserRouter as Router } from 'react-router-dom'; import Home from './Home'; import Detail from './Detail'; const App = () => ( <Router> <div> <Route exact path="/" component={Home} /> <Route path="/detail/:id" component={Detail} /> </div> </Router> ); export default App;
- 在主页中添加链接:
import { Link } from 'react-router-dom'; const Home = () => ( <div> <h2>Home</h2> <ul> <li><Link to="/detail/1">Detail 1</Link></li> <li><Link to="/detail/2">Detail 2</Link></li> <li><Link to="/detail/3">Detail 3</Link></li> </ul> </div> ); export default Home;
- 在详情页中获取参数:
import { useParams } from 'react-router-dom'; const Detail = () => { let { id } = useParams(); return ( <div> <h2>Detail {id}</h2> </div> ); } export default Detail;
此时点击链接会跳转到对应的详情页,并在详情页中显示传递的参数。