react跳转和传参两种方式

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

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

1.useSearchParams传参

 传参代码

//传参方代码
import { Link, useNavigate } from "react-router-dom"
const Login = () =>{
    const navigate = useNavigate()
    return 
跳转到购物(传参)
} 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:
    },
    {
        path:'/my/:id/:name',
        element:
    }
])

export default router

 传参代码

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


const Login = () =>{
    const navigate = useNavigate()
    return 
跳转到我的(传参)
} export default Login

接收代码

//接收方
import { useParams } from "react-router-dom"
const My = () =>{
    const params = useParams()
    const id = params.id
    const name = params.name
    return 
这里是我的页面,id是{id},名字是{name}
} export default My

你可能感兴趣的:(react,前端例子,react.js,前端,前端框架)