简体   繁体   English

在 JSX 中传播具有相同属性的多个道具

[英]Spreading multiple props with the same property in JSX

Given two props objects:给定两个 props 对象:

const p1 = {
  id: "p1"
  //...
}

const p2 = {
  id: "p2"
  //...
}

If spreading them both on the same component, like:如果将它们都分布在同一个组件上,例如:

<MyComponent {...p1} {...p2}/>

How React is to determine what property value id to use? React 如何确定要使用的属性值id

May also consider other cases like也可以考虑其他情况,例如

<MyComponent {...p1} id={"p3"} {...p2}/>
<MyComponent id={"p3"} {...p1} {...p2}/>

Basically, whats the rule behind to tell which property value is the value it uses?基本上,告诉哪个属性值是它使用的值背后的规则是什么?

In the order they appear, left to right.按照它们出现的顺序,从左到右。 It'll walk through the first spread, assigning props, then through the second, overwriting any duplicates.它将遍历第一个传播,分配道具,然后通过第二个,覆盖所有重复项。

Demonstration:示范:

const Printout = (props: { x: number; y: number; z: number }) => {
  useEffect(() => console.log(props), [props]);
  return null;
};

const Demo = () => {
  const a = { x: 1, y: 2, z: 3 };
  const b = { y: 5, x: 6 };
  return <Printout {...a} z={4} {...b} />;
};

Console output:控制台 output:

{"x": 6, "y": 5, "z": 4}

The order that keys are obtained from an object is a different question.从 object 获取密钥的顺序是另一个问题。 See Does JavaScript guarantee object property order?请参阅JavaScript 是否保证 object 属性订单? for example.例如。

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

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