【React-Router】导航传参

1. searchParams 传参

// @/page/Login/index.js
import { Link, useNavigate } from 'react-router-dom'
const Login = () => {
  const navigate = useNavigate()
  return <div>
    登录页
    <button onClick={() => navigate('/article?id=91&name=jk')}>searchParams 传参</button>
    </div>
}

export default Login
// @/page/Article/index.js
import { useSearchParams } from "react-router-dom";
const Article = () => {
const [params] = useSearchParams();
  const id = params.get('id');
  const name = params.get('name');
  return <div>文章页,接收参数{id}-{name}</div>
}

export default Article

【React-Router】导航传参_第1张图片

2. params 传参

// @/page/Login/index.js
import { Link, useNavigate } from 'react-router-dom'
const Login = () => {
  const navigate = useNavigate()
  return <div>
    登录页
    <button onClick={() => navigate('/article/91/jk')}>Params 传参</button>
    </div>
}

export default Login
// @/page/Article/index.js
import { useParams, useSearchParams } from "react-router-dom";
const Article = () => {
  const params = useParams()
  const id = params.id
  const name = params.name
  return <div>文章页,接收参数{id}-{name}</div>
}

export default Article
// @/router.index.js
import Login from '../page/Login'
import Article from '../page/Article'
import { createBrowserRouter } from 'react-router-dom'
const router = createBrowserRouter([
  {
    path: '/login',
    element: <Login></Login>
  },
  {
    // `/:id/:name` 占位符
    path: '/article/:id/:name',
    element: <Article></Article>
  },
  {
    path: '/',
    element: <Login></Login>
  }
])

export default router

【React-Router】导航传参_第2张图片

你可能感兴趣的:(React-Router,react.js,javascript,前端)