[英]Spread operator to pass all other props to a component. React.js
I'm having trouble understanding the spread operator when I want to pass all other props to a component.当我想将所有其他道具传递给组件时,我无法理解传播运算符。
Any help would be appreciated.任何帮助,将不胜感激。
import React, { Fragment } from "react";
import SiteCard from "./SiteCard";
const SiteList = ({ sites }) => {
return (
<Fragment>
{sites.map((site) => {
return (
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
otherSiteProps={...site} // how can I pass the site props here?
/>
);
})}
</Fragment>
);
};
export default SiteList;
You are almost there with the solution.您几乎可以找到解决方案。
You need to pass it as otherSiteProps={{...site}}
.您需要将其作为
otherSiteProps={{...site}}
传递。 This is if you want to pass site
as an object to otherSiteProps
property of SiteCard
.这是如果您想将
site
作为 object 传递给SiteCard
的otherSiteProps
属性。
If you want to spread site
and have multiple props for component SiteCard
you do it like this:如果您想传播
site
并为组件SiteCard
拥有多个道具,您可以这样做:
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
{...sites}
/>
This in case that sites
is an object.如果
sites
是 object。 If site
is an array, this wont work.如果
site
是一个数组,这将不起作用。
You just need to write:你只需要写:
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
{...site} // how can I pass the site props here?
/>
But wait, why you're making so complicated?但是等等,你为什么要搞得这么复杂? You can just use:
您可以使用:
<SiteCard {...site} />
Now, in your SiteCard component use required props.现在,在您的 SiteCard 组件中使用所需的道具。
And if I were you, I would not have separated SiteCard
component for this scenario.如果我是你,我不会在这种情况下分离
SiteCard
组件。 I would just write:我只想写:
{sites.map((site) => {
return (
// everything here I will utilize in html.
);
})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.