react官方太任性了,为了推荐函数式组件,最新版路由传参似乎必须使用函数式组件
父组件 <Message/> :
import React, { Component } from 'react'
import { Link, Route,Routes} from 'react-router-dom'
import {Detail} from './Detail'
export default class Message extends Component {
state = {
list: [
{ id: '001', title: '消息1' },
{ id: '002', title: '消息2' },
{ id: '003', title: '消息3' }
]
}
render() {
return (
<div>
<ul>
{
this.state.list.map(i => (
<li key={i.id}>
{/* 向路由组件传递params参数,直接拼 */}
<Link to={`/home/message/detail/${i.id}/${i.title}`}>{i.title}</Link>
</li>
))
}
</ul>
<hr />
<Routes>
{/* 声明接收params参数 */}
<Route path='detail/:id/:title' element={<Detail/>}></Route>
</Routes>
</div>
)
}
}
子组件 <Detail/> :
import React, { Component } from 'react'
import { useParams } from 'react-router-dom'
export const Detail = () => {
const data = [
{id:'001',content:'你好,中国'},
{id:'002',content:'你好,未来'},
{id:'003',content:'你好,小彭'}
]
const params = useParams()
console.log('detail组件参数:', params)
return (
<ul>
<li>ID:{params.id}</li>
<li>TITLE:{params.title}</li>
<li>CONTENT:{data.filter(i => i.id == params.id)[0].content}</li>
</ul>
)
}
教程里面老师用的都是类式组件,api也都是v5的,学的好蓝瘦