实现效果——点击展台1、展台2、展台3时,会显示同一个名为Detail路由组件,但是组件接收的值会不一样:
文件目录:
Message>index.jsx:
import React, { Component } from 'react'
import { Link, Route } from 'react-router-dom'
import Detail from './Detail';
export default class Message extends Component {
constructor() {
super();
this.state = {
messageArr: [
{ id: "01", title: '展台1' },
{ id: "02", title: '展台2' },
{ id: "03", title: '展台3' }
]
}
}
render() {
const { messageArr } = this.state
return (
<div>
<ul>
{
messageArr.map((msgObj) => {
return (
<li key={msgObj.id}>
{/* 1.向路由组件传递params参数 */}
<Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>
</li>
)
})
}
</ul>
<hr />
{/* 2.声明接收params参数 */}
<Route path='/home/message/detail/:id/:title' component={Detail} />
</div>
)
}
}
Message>Detail>index.jsx:
import React, { Component } from 'react'
const DetailData = [
{ id: '01', content: '你好,01' },
{ id: '02', content: '你好,02' },
{ id: '03', content: '你好,03' },
]
export default class Detail extends Component {
render() {
//3.接收params参数
const { id, title } = this.props.match.params//解构赋值
const findResult = DetailData.find((detailObj) => {
return detailObj.id === id //如果某一项对象的id和我传过来的Id相等,findResult就等于这一项对象
})
return (
<ul>
<li>id:{id}</li>
<li>title:{title}</li>
<li>content:{findResult.content}</li>
</ul>
)
}
}