admin管理员组文章数量:1418612
I'm having trouble understanding the spread operator when I want to pass all other props to a ponent.
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;
I'm having trouble understanding the spread operator when I want to pass all other props to a ponent.
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;
Share
Improve this question
asked Jul 28, 2020 at 11:37
kimo26kimo26
1111 gold badge4 silver badges15 bronze badges
1
-
1
simply write
{site}
instead of{...site}
– Atul Kumar Commented Jul 28, 2020 at 11:40
2 Answers
Reset to default 4You 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 plicated? You can just use:
<SiteCard {...site} />
Now, in your SiteCard ponent use required props.
And if I were you, I would not have separated SiteCard
ponent for this scenario. I would just write:
{sites.map((site) => {
return (
// everything here I will utilize in html.
);
})}
You are almost there with the solution.
You need to pass it as otherSiteProps={{...site}}
.
This is if you want to pass site
as an object to otherSiteProps
property of SiteCard
.
If you want to spread site
and have multiple props for ponent SiteCard
you do it like this:
<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. If site
is an array, this wont work.
本文标签: javascriptSpread operator to pass all other props to a component ReactjsStack Overflow
版权声明:本文标题:javascript - Spread operator to pass all other props to a component. React.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745293006a2651910.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论