首页 > 解决方案 > 如何在 URL 中传递值以及如何在 React JS 中从 URl 获取值

问题描述

如何在 React js 中的 URL 中传递值以及如何在 React js 中从 URL 中获取值 步骤 1. 在 Link/Button 中编写代码

<Link to={{pathname:`/MediaLandingPage/${props.data.id}`}}>{props.linkName}</Link>

步骤 2. 在路由器路径中设置

<Route path="/MediaLandingPage/:id" component={MediaLandingPage} />

步骤 3. 创建页面 MediaLandingPage

const MediaLandingPage =(props)=>{
    const id =props.match.params.id
    var ImageData = require('../../Media/image.js')
    var data = ImageData.default
    console.log("Media :",data)
    if(data[id].id==id){
        return<div className=""> 
                    <div><Image src={data[id].imageSrc} className="img-fluid"/></div>
                    <div>{data[id].title}</div>
                    <div>{data[id].description}</div>

                </div>
    }else
    {
        return<div>Sorry</div>
    }
}
export default MediaLandingPage

步骤 4. 数据 image.js 文件

import safeCitizens from "../../assets/images/safeCitizens.png" 
export default[
    {
        id:0,
        imageSrc:safeCitizens,
        title:"name",
        shortDescription:"asfddasf",
        description:"chandra veer singh rathorchandra veer singh rathor"
    },
    {
        id:1,
        imageSrc:safeCitizens,
        title:"name",
        shortDescription:"asfddasf",
        description:"chandra veer singh rathorchandra veer singh rathor"
    },
    {
        id:2,
        imageSrc:safeCitizens,
        title:"name",
        shortDescription:"asfddasf",
        description:"chandra veer singh rathorchandra veer singh rathor"
    } 
]

标签: reactjs

解决方案


解决方案 1:

第 1 步:在此处直接传递您的 id 以进行路由

<Link to={`/MediaLandingPage/${props.data.id}`}>{props.linkName}</Link>

第 2 步:使用访问您的数据

this.props.match.params.id

解决方案2:您可以参考我的答案

 you can directly pass your id with link 

推荐阅读