1 路由固定 ----navlink 传值 params传参 useParams
//路由 import { Outlet,NavLink } from 'react-router-dom' { path:'detail/:id/:title/:content', element:<Detail /> } //组件内点击 <li> <NavLink to={`detail/${item.id}/${item.title}/${item.content}`} >{item.title}</NavLink> </li> //组件内接受参数 import { useParams } from 'react-router-dom' export default function Detail() { let {id,title,content} = useParams() return ( <div> <ul> <li>新闻id:{id}</li> <li>新闻标题:{title}</li> <li>新闻内容:{content}</li> </ul> </div> ) }
2路由传值 query传参 useSearchParams
//路由 import { Outlet,NavLink } from 'react-router-dom' { path:'detail', element:<Detail /> } //组件内点击 <li> <NavLink to={`detail?id=${item.id}&title=${item.title}&content=${item.content}`}>{item.title}</NavLink> </li> //组件内接受参数 第一个参数传递过来的数据对象,用get方法来取值 第二个参数是设置新的数据 import { useSearchParams } from 'react-router-dom' export default function Detail() { let [searchParams,setobj] = useSearchParams() let id = searchParams.get('id') let title = searchParams.get('title') let content = searchParams.get('content') return ( <div> <ul> <li>新闻id:{id}</li> <li>新闻标题:{title}</li> <li>新闻内容:{content}</li> <li onClick={()=>{ setobj( { id: 4, title: "你是谁啊4", content: "有什么事情啊4" }) }}>点击切换</li> </ul> </div> ) }
3.state传参 useLocation
//路由 import { Outlet,NavLink } from 'react-router-dom' { path:'detail', element:<Detail /> } //组件内点击 <li> <NavLink to='detail' state={item}>{item.title}</NavLink> </li> // state传参 import React from 'react' import { useLocation } from 'react-router-dom' export default function Detail() { let {state:{id,title,content}} = useLocation() return ( <div> <ul> <li>新闻id:{id}</li> <li>新闻标题:{title}</li> <li>新闻内容:{content}</li> </ul> </div> ) }