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