[英]How can I pass multiple values in a single prop in react?
Is there any way where I can pass in multiple values in a single prop?有什么方法可以在单个道具中传递多个值?
Right now how it works is I have one component and it takes in lots of values like this:现在它的工作原理是我有一个组件,它包含很多这样的值:
<div>
<MyComponent
valueA={100}
valueB={90}
valueC={80}
valueD={70}
valueE={60}
/>
</div>
Here for example A and B are related and I want to pass them together like例如,这里 A 和 B 是相关的,我想将它们一起传递
<div>
<MyComponent
valueAB={100, 90}
valueC={80}
valueD={70}
valueE={60}
/>
</div>
It probably needs to be in a single object like this: valueAB={{100, 90}}
but I have no idea.它可能需要像这样在单个 object 中:
valueAB={{100, 90}}
但我不知道。
How can I do this and extract both of the values on the other side?我怎样才能做到这一点并提取另一侧的两个值?
You can pass an array or an object:您可以传递一个数组或 object:
// e.g
<MyComponent
valueAB={[100, 90]}
valueC={{ a: 100, b: 90}} />
And in MyComponent you will get valueAB prop as array, hence you can do something like:在 MyComponent 中,您将获得 valueAB 属性作为数组,因此您可以执行以下操作:
props.valueAB[0] // 100
Or for objet: props.valueC.a
is also 100.或者对于对象:
props.valueC.a
也是 100。
I think you can do add them as a one object as you did {{100, 90}} or one array {[100,90]}我认为您可以将它们添加为一个 object 就像您所做的 {{100, 90}} 或一个数组 {[100,90]}
and you can easily extract them from the array like this:您可以像这样轻松地从数组中提取它们:
let myCompValueABFirst = props.valueAB[0];
let myCompValueABSecond = props.valueAB[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.