简体   繁体   English

传播 React Props 的令人困惑的语法

[英]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?我了解如何使用扩展运算符以及如何轻松地将其余任何其他道具传播给 React 孩子,但是有人可以向我解释为什么这个人要在 RoundedIcon 组件的已经解构的道具“背景颜色”中添加额外的花括号?

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.在您的上述情况下,传播{...{ backgroundColor }}会将 props 中的backgroundColor传递给子组件。 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}更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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