简体   繁体   中英

Confusing Syntax of Spreading React Props

const RoundedIcon = ({
  name,
  size,
  color,
  backgroundColor,
}: RoundedIconProps) => {
  return (
    <Box
      height={size}
      width={size}
      justifyContent="center"
      alignItems="center"
      style={{ borderRadius: size / 2 }}
      {...{ backgroundColor }}
    />
  );
};

I understand how to use the spread operator and how you can easily spread the rest of any additional props to a React child, but can someone explain to me why this person is adding extra curly braces to an already destructered prop 'backgroundColor' of RoundedIcon component?

In my opinion, it does not make sense. It may just be an artefact of this person doing:

{...{ backgroundColor, name, color }}

and then not needing name or color anymore to be spreaded in the props. So leaving

{...{ backgroundColor }}

Because it's exactly the same as:

backgroundColor={backgroundColor}

After writing this, I realized that it may be faster to type, and so you don't have a messy two times 'backgroundColor' in your code.

In your case above spreading {...{ backgroundColor }} will pass backgroundColor in props to the child component. But if you want to rename the variable you have to spread it like below:

function ComponentA() {
  const backgroundColor = "red";

  return (
    <div>
      <p>Component A</p>
      <ComponentB {...{ helloWorld: backgroundColor }} />
    </div>
  );
}

function ComponentB(props) {
  console.log(props); // { helloWorld: "red" }

  return <div>Component B</div>;
}

我怀疑这{...{ backgroundColor }}是否比backgroundColor={backgroundColor}更好

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