[英]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 }}
/>
);
};
我了解如何使用扩展运算符以及如何轻松地将其余任何其他道具传播给 React 孩子,但是有人可以向我解释为什么这个人要在 RoundedIcon 组件的已经解构的道具“背景颜色”中添加额外的花括号?
在我看来,这没有意义。 这可能只是这个人做的一个人工制品:
{...{ backgroundColor, name, color }}
然后不再需要名称或颜色来散布在道具中。 所以离开
{...{ backgroundColor }}
因为它完全一样:
backgroundColor={backgroundColor}
写完这篇文章后,我意识到打字可能会更快,所以你的代码中不会有一个凌乱的两次“背景颜色”。
在您的上述情况下,传播{...{ backgroundColor }}
会将 props 中的backgroundColor
传递给子组件。 但是如果你想重命名变量,你必须像下面这样传播它:
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.