关于react.js:React-向路由组件传递-params-参数

50次阅读

共计 1004 个字符,预计需要花费 3 分钟才能阅读完成。

传递参数组件的 jsx 文件:

import React, {Component} from 'react'
import {Switch,Route,Link} from 'react-router-dom'
import Detail from './Detail'

export default class Message extends Component {
  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}>
                  {/* 向路由组件传递 params 参数 */}
                  <Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>
                </li>
              ) 
            })
          }
        </ul>
        <hr/>
        {/* 注册路由 申明接管 params*/}
        <Switch>
          <Route path='/home/message/detail/:id/:title' component={Detail}></Route>
        </Switch>
      </div>
    )
  }
}

接管参数组件的 jsx 文件:

import React, {Component} from 'react'

const detailData = [{id:'01',content:'你好,中国'},
  {id:'02',content:'你好,上海'},
  {id:'03',content:'你好,北京'}
]

export default class Detail extends Component {render() {
    // 接管 params 参数
    const {id,title} = this.props.match.params
    const findResult = detailData.find((detailObj)=>{return detailObj.id === id})
    return (
      <div>
          <li>ID:{id}</li>
          <li>Title:{title}</li>
          <li>Content:{findResult.content}</li>
      </div>
    )
  }
}

正文完
 0