react跳转和传参两种方式

2023-12-27 21:09:18

需要安装ReactRouter包:npm i react-router-dom

两种跳转方式分别是LinkuseNavigate,下面跳转传参会有所展示

1.useSearchParams传参

?传参代码

//传参方代码
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

接收代码?

//接收方代码
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传参

//路由这里需要进行配置(主要看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

?传参代码

//传参方
import { Link, useNavigate } from "react-router-dom"


const Login = () =>{
    const navigate = useNavigate()
    return <div>
        <Link to="/my/100/ll">跳转到我的(传参)</Link>
    </div>
}
export default Login

接收代码

//接收方
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

文章来源:https://blog.csdn.net/qq_35181466/article/details/135248459
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。