需要安装ReactRouter包:npm i react-router-dom
两种跳转方式分别是Link和useNavigate,下面跳转传参会有所展示
1.useSearchParams传参
传参代码
javascript
//传参方代码
import { Link, useNavigate } from "react-router-dom"
const Login = () =>{
const navigate = useNavigate()
return <div>
<button onClick={()=>navigate('/shop?id=100&name=zs')}>登录(传参)</button>
<Link to="/shop?id=100&name=zs">跳转到购物(传参)</Link>
</div>
}
export default Login
接收代码
javascript
//接收方代码
import { useSearchParams } from "react-router-dom"
function App(){
// 接收传参
const [params] = useSearchParams()
const id = params.get('id')
const name = params.get('name')
console.log(id, '接收传参', name)
}
2.useParams传参
javascript
//路由这里需要进行配置(主要看my的配置)
import Login from '../view/login/index'
import My from '../view/my/index'
import { createBrowserRouter } from 'react-router-dom'
const router = createBrowserRouter([
{
path:'/login',
element:<Login/>
},
{
path:'/my/:id/:name',
element:<My/>
}
])
export default router
传参代码
javascript
//传参方
import { Link, useNavigate } from "react-router-dom"
const Login = () =>{
const navigate = useNavigate()
return <div>
<Link to="/my/100/ll">跳转到我的(传参)</Link>
</div>
}
export default Login
接收代码
javascript
//接收方
import { useParams } from "react-router-dom"
const My = () =>{
const params = useParams()
const id = params.id
const name = params.name
return <div>
<div>这里是我的页面,id是{id},名字是{name}</div>
</div>
}
export default My