javascript - 通过组件发送数据
问题描述
我有这个我无法解决的问题。所以基本上我这里有 2 个组件,组件 A 和组件 GI 有更多,但它们几乎相同(概念相同)。我在组件 G、A 中有一个链接,当我单击它时,它会将我带到支付组件。Tt 现在将(ImageA、ClassA 和 PriceA)呈现为硬编码。无论如何,我想要实现的是,例如,当我单击组件 G 时,它只会呈现(imageG、classG 和 priceG),所以我需要它以某种方式过滤它或以某种方式在我想象的 json 文件中拆分数据,但我不知道该怎么做。我希望你们中的一位同志能帮助我。
Payment Component
const Payment = ({
history,
location: { state },
match: {
params: { dataId }
}
}) => {
if (!state?.postData) {
history.goBack();
}
const { postData } = state;
return (
<div className="ml-20">
<img
alt=""
className="w:2/4 object-contain "
src={postData.imageG}
/>
<h2
className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-blue-400 absolute top-
48" >
{postData.classG}
</h2>
<h3
className="text-lg mlg:mb-2 mlg:ml-6 mlg:mt-2 mlg:static font-bold text-green-800
font-mono ml-24 top-64 absolute"
>
{postData.priceG}
</h3>
</div>
);
};
export default Payment
A COMPONENT
import React from "react";
import data from "../data.json";
import { Link } from "react-router-dom";
function A() {
return (
<div className='bg-black '>
{data.filter(d =>
d.classA &&
d.imageA &&
d.priceA)
.map((postData) => {
return (
<div className='bg-black' key={postData.id} >
<div className='bg-black '>
<img
alt=""
className="w-full object-contain "
src={postData.imageA}
></img>
<h1 className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-red-600
absolute top-48">
{postData.classA}
</h1>
<h1 className="text-lg mlg:mb-2 mlg:ml-6 mlg:mt-2 mlg:static font-bold text-yellow-600
font-mono ml-24 top-64 absolute" >
{postData.priceA}
</h1>
<Link
to={{pathname: `/payment/${postData.id}`,
state: {
postData,
},
}}
className="py-1 px-2 mlg:ml-6 mlg:mt-14 mlg:static text-black-600 h-8 ml-24 top-72 bg-
white w-32 text-center text-gray-red
rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600 absolute"
>
Buy Now
</Link>
</div>
</div>
</div>
)
}
export default A
G Component
import React from "react";
import data from "../data.json";
import { Link } from "react-router-dom";
function G() {
return (
<div className='bg-black '>
{data.filter(d =>
d.classG &&
d.imageG &&
d.priceG)
.map((postData) => {
return (
<div className='bg-black' key={postData.id} >
<div className='bg-black '>
<img
alt=""
className="w-full object-contain "
src={postData.imageG}
></img>
<h1 className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-red-600
absolute top-48">
{postData.classG}
</h1>
<h1 className="text-lg mlg:mb-2 mlg:ml-6 mlg:mt-2 mlg:static font-bold text-yellow-600
font-mono ml-24 top-64 absolute" >
{postData.priceG}
</h1>
<Link
to={{pathname: `/payment/${postData.id}`,
state: {
postData,
},
}}
className="py-1 px-2 mlg:ml-6 mlg:mt-14 mlg:static text-black-600 h-8 ml-24 top-72 bg-
white w-32 text-center text-gray-red
rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600 absolute"
>
Buy Now
</Link>
</div>
</div>
</div>
)
}
export default G
Json file
[
{
"id":0,
"classG":"G-Class",
"imageG":"./ModImages/Gclass.jpg",
"priceG":"Starting at $154,900",
"newG":"A 12.3-inch digital gauge cluster is newly standard across the
board, as are heated front seats. Plus, the sedan can be had with a Night
package that adds black exterior trim.",
"imageGIn":"./ModImages/GclassIn.jpg",
"imageCOut":"./ModImages/GclassOut.jpg",
"infoDesignC1":"How many technological breakthroughs can you fit into a C-
Class? With the advanced, powerful and sporty 2020 C 300 Wagon, plenty. From
its LED headlamps to its generous cargo hold, you'll find countless
refinements, and so many reasons it's a wagon like no other.",
"infoDesignG" :"The acclaimed C-Class cabin is as functional as it is
beautiful. Abundant innovations harmonize with five options in hand-finished
wood trim. A 12.3-inch digital instrument cluster and 10.25-inch centre
screen are available.",
"imageGIn1":"./ModImages/CclassIn1.jpg",
"imageGOut1":"./ModImages/CclassOut1.jpg",
"infoDesign2": "The Star on the outside is earned on the inside. The roomy,
refined cabin includes heated front seats and a driver-seat memory. Dual-
zone, double-filtered climate control. A panoramic sunroof. And options from
Burmester® surround sound to new Climate Comfort front seats.",
"infoInov": "Available Apple CarPlay™ and Android Auto let you enjoy more
from your own smartphone. Another navigation option is COMAND, which brings
you voice control not only for navigation and audio, but also many cabin
features.",
"imageInov1":"./ModImages/GclassInov1.jpg",
"imageInov2":"./ModImages/GclassInov2.jpg",
"infoInov1": "Available wireless charging lets you refuel your compatible
phone's battery as you drive. Easy-connect NFC pairing links your phone
every
time you get in. Apple CarPlay™ and Android Auto are available, too. And
four USB-C ports are standard.",
"infoInov2": "DYNAMIC SELECT lets you fine-tune your A-Class with the tap of
a console button. Four modes vary shift points, throttle response, steering
feel and more: efficient ECO, everyday Comfort, sharpened Sport, and create-
your-own Individual.",
"imageInov":"./ModImages/GclassInov.jpg",
"imageInov4":"./ModImages/GclassInov4.jpg" ,
"infoInov4G": "From the everyday to the unexpected, Mercedes me connect helps
ease your way. You can control vehicle features from your smartphone
(including Remote Start), set up a service appointment, and more. You can
also add In-car Wi-Fi for a low monthly rate. ",
"infoInov5C":"Available driver assists help de-stress driving, changing lanes
with a tap of your finger, and knowing to slow for a tollboth or exit. A
network of sensors keeps a constant lookout for danger ahead, even if it's
coming from behind."
},
{
"id":1,
"classA":"A-Class",
"imageA":"./ModImages/Aclass.jpg",
"priceA":"Starting at $54,900",
"newA":"In addition to a new 18-inch wheel design, the 2021 A-class gains
standard blind-spot monitoring and an optional gesture control feature for
the MBUX infotainment system.",
"imageAIn":"./ModImages/AclassIn.jpg",
"imageAOut":"./ModImages/AclassOut.jpg",
"infoDesignA":"A is for attention-getting. The clean lines, LED lighting and
aggressive stance of the A-Class Sedan are designed to capture admiring eyes.
Its ultramodern cabin and premium appointments aim to captivate its driver
and passengers for years to come.",
"infoDesignA1" :"With 100% LED lighting standard, inside and out, the A-Class
shines day or night, coming or going, and staying, too. Options include
MULTIBEAM LED headlamps and 64-colour ambient cabin lighting.",
"imageAIn1":"./ModImages/AclassIn1.jpg",
"imageAOut1":"./ModImages/AclassOut1.jpg",
"infoDesignA2": "The Star on the outside is earned on the inside. The roomy,
refined cabin includes heated front seats and a driver-seat memory. Dual-
zone, double-filtered climate control. A panoramic sunroof. And options from
Burmester® surround sound to new Climate Comfort front seats.",
"infoInov": "A is for advanced. With the Mercedes-Benz User Experience
(MBUX), the A-Class drives a new generation of user-friendly tech. Quite
possibly the most capable, natural and intuitive speech interface from any
automaker, it's easy to learn because it learns you.",
"imageInov1":"./ModImages/AclassInov1.jpg",
"imageInov2":"./ModImages/AclassInov2.jpg",
"infoInov1": "Available wireless charging lets you refuel your compatible
phone's battery as you drive. Easy-connect NFC pairing links your phone
every time you get in. Apple CarPlay™ and Android Auto are available, too.
And four USB-C ports are standard. Disclaimer[6] Disclaimer",
"infoInov2": "DYNAMIC SELECT lets you fine-tune your A-Class with the tap of
a console button. Four modes vary shift points, throttle response, steering
feel and more: efficient ECO, everyday Comfort, sharpened Sport, and create-
your-own Individual.",
"imageInov3":"./ModImages/AclassInov3.jpg",
"imageInov4":"./ModImages/AclassInov4.jpg" ,
"infoInov4": "Get up close with the A-Class Sedan in this captivating ASMR audio experience. "
}
]
解决方案
我正在根据评论更新答案
首先,我会确保我的 JSON 属性在对象之间是一致的:
[
{
"id":0,
"class":"G-Class",
"image":"./ModImages/Gclass.jpg",
"price":"Starting at $154,900",
"new":"Mercedes-Benz introduces a mid-cycle update of the E-class lineup for 2021. The changes
apply",
"infoInov": "....",
"imageOut": "..."
},
{
"id":1,
"class":"A-Class",
"image":"./ModImages/Aclass.jpg",
"price":"Starting at $54,900",
"new":"Mercedes-Benz introduces a mid-cycle update of the E-class lineup for 2021. The changes
apply",
"infoInov": "....",
"imageOut": "..."
}
]
由于所有属性都是一致的,因此您可以始终如一地区分它们的唯一方法是通过id
属性。如果id === 0
,我们知道它是 G. if === 1
,我们知道它是 A ,依此类推。
这样,我可以只使用一个组件来渲染它们。如果您想应用不同的样式或渲染某些东西(如果它是组件 G),您可以执行以下操作:
function AG() {
return (
<div className="bg-black">
{data.map(product => (
<div>
<img src={product.image} />
<h1>{product.class}</h1>
<h1 className={product.id === 0 ? 'g-class' : ''}>{product.price}</h1>
<Link to={`/payment/${product.id}` />
{product.id === 0 && <div>This will only appear to G</div>}
</div>
))}
</div>
)
}
请注意,我有一些检查来应用样式或仅在product.id === 0
. 这是重用组件并对其应用少量更改的方法之一。
在<Link>
我们发送用户/payments
在路径中传递产品ID。因此,在Payments
组件内部,您将使用此 productID 过滤来自 JSON 的数据。
现在在支付组件中,您可以导入相同的 JSON并通过我们在 URL 路径中传递的data
过滤器:id
import data from "../data.json"
const Payment = () => {
// get the id from the URL somehow, I suppose you are using react router
// this is just an example
const { idFromURL } = match.param
const filteredProduct = data.filter(product => product.id === idFromURL)
return (
<div>
<img src={filteredProduct.image} />
</div>
)
}
现在该filteredProduct
变量具有 A 或 G 的数据,您可以使用它在 Payment 组件中显示您想要的特定数据。
推荐阅读
- python - 进程在后台运行时在 kivy 中显示某些内容
- c# - GoogleAnalyticsTracker 为 winforms 应用程序创建独特的会话
- powershell - WMI 返回非活动笔记本电脑显示器的分辨率
- linux - Ansible 任务写入本地日志文件
- visual-studio-code - 如何通过 Google Chrom 扩展在浏览器脚本中调试 Nuxt
- api - React Native API Fetch 没有完全发生。映射时抛出错误
- c++ - 我无法使用 c++(代码块)中的 fstream 将文件内容复制到另一个。如何运行该文件?
- wordpress - 在保存时自定义 ACF 选项页面值
- android - Android,使用 FFMPEG 分割 GIF 不起作用
- javascript - 如何在 html 中添加更多半列,例如 0.5, 1.5 ,2..5