简体   繁体   中英

Passing react props as object

I find this syntax so weird.

     <>
      {items.map((item, i) => {
        return <ItemComponent key={i} {...{ [resourceName]: item }} />;
      })}
    </>

Can you explain it please? I know that in Parent component now I get name prop, but IDK how did this happen..

I don't have the full context so here's my guess:

resourceName is a variable describing which prop will be set on ItemComponent.

you can't write resourceName={item} because then ItemComponent would have a property "resourceName" instead of whatever value is stored inside resourceName .

So the workaround for this is to create an object with only one key being the value of resourceName associated to the item object:

const itemComponentProps = {
  [resourceName]: item;
};

If you are not familiar with this syntax, it's to use dynamic keys on objects.

example:

const dynamicKey = 'foo';
const obj = {
  [dynamicKey]: 'bar'
}
console.log(obj[dynamicKey]); // bar
console.log(obj.foo); // bar

and you spread this object to the component:

<ItemComponent key={i} {...itemComponentProps} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM