如何解决如何从 onClick 获取特定数据并将其显示到 React 中的另一个页面
所以我目前正在做一个 React 项目,我想弄清楚如何从点击的按钮/配置文件中获取特定数据,然后将其显示到另一个页面上。
这是我目前拥有的。这是当前显示在主页上的不同名人的个人资料列表。每个都显示为个人资料卡片,您可以点击该卡片。
import React from 'react';
import '../styles/Profile.css';
import ProfileItems from '../components/ProfileItems';
function profile() {
return (
<div className='profile'>
<h1>Choose A Profile</h1>
<div className='profile__container'>
<div className='profile__wrapper'>
<ul className='profile__items'>
<ProfileItems
src='images/KimK.jpg'
text='Kim Kardashian - Skims'
label='Social Media Influncer'
path='/'
/>
<ProfileItems
src='images/TheRock.jpg'
text='The Rock - Zoa Energy Drink'
label='Pressional Wrestler & Actor'
path='/'
/>
</ul>
<ul className='profile__items'>
<ProfileItems
src='images/Ronaldo.jpg'
text='Cristiano Ronaldo - Portugal Team'
label='Professional Soccer Player'
path='/'
/>
<ProfileItems
src='images/Kylie.jpg'
text='Kylie Jenner - Kylie Cosmetics'
label='Social Media Influncer'
path='/'
/>
<ProfileItems
src='images/Elon.jpg'
text='Elon Musk - Tesla'
label='CEO'
path='/'
/>
</ul>
</div>
</div>
</div>
);
}
export default profile;
现在对于这些配置文件中的每一个,当它们被点击时,我希望它们被专门路由或设置为带有各自数据的另一个页面的路径。例如,我有这个 JSON 文件,其中包含有关 Kylie Jenner 和 Kim Kardashian 的信息。因此,当我点击 Kylie Jenner 的个人资料时,我希望从 JSON 文件中提取数据,并且只提取 Kylie 的数据并将该数据显示在我设置为“分析页面”的另一个页面上。
[
{
"id": 1,"title": "Kylie Jenner","content": "Social Media Public figure","disclaimer": "*disclaimer: This user Could have comment filtering turned on","slug": "hello-world","img" : "https://ilarge.lisimg.com/image/16801290/1080full-kylie-jenner.jpg"
},{
"id": 2,"title": "Kim Kardashian","img" : ""
}
]
金·卡戴珊等其他名人也是如此。因此,当我单击 Kim 的个人资料时,只会从 JSON 文件中提取她的数据。拉取后,我希望将其显示在我在下面设置的“分析页面”上。
import React,{ Component } from 'react'
export class Analysis extends Component {
render() {
return (
<div>
</div>
)
}
}
export default Analysis
我相信我必须设置一个 onClick 函数,但我对如何/在何处设置该 onClick 函数以获取特定数据感到困惑。然后路由配置文件并将其显示到另一个页面上。如果有人可以指导我或提出更简单的方法,请告诉我。将不胜感激。
解决方法
您需要使用 react-router-dom
在 props 中传递名人姓名(在您的案例中为头衔)。然后,在您的分析页面中,您可以使用道具从数据库中检索相关信息。
在此处查看我的演示:https://stackblitz.com/edit/react-gkpswn?file=src%2FApp.js
ProfileItems.js
// Link to analysis route with title in props
<Link to={`/analysis/${title}`}>
App.js
// Route to analysis page/component with title props
<Route path="/analysis/:title" render={props => <Analysis {...props} />} />
Analysis.js
// Get the props with useParams (react-router-dom)
const { title } = useParams();
// filter data to get informations based on props "title"
const profile = Data.filter(profile => profile.title === title);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。