最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I pass multiple values in a single prop in react? - Stack Overflow

programmeradmin2浏览0评论

Is there any way where I can pass in multiple values in a single prop?

Right now how it works is I have one ponent 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

<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.

How can I do this and extract both of the values on the other side?

Is there any way where I can pass in multiple values in a single prop?

Right now how it works is I have one ponent 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

<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.

How can I do this and extract both of the values on the other side?

Share asked Feb 27, 2021 at 12:53 Devesh KumarDevesh Kumar 1861 gold badge4 silver badges19 bronze badges 1
  • Just pass an array or object as a prop. – Robin Zigmond Commented Feb 27, 2021 at 12:56
Add a ment  | 

2 Answers 2

Reset to default 9

You can pass an array or an 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:

props.valueAB[0] // 100

Or for objet : props.valueC.a is also 100 .

I think you can do add them as a one object as you did {{100, 90}} or one array {[100,90]}

and you can easily extract them from the array like this:

let myCompValueABFirst = props.valueAB[0];
let myCompValueABSecond = props.valueAB[1];
发布评论

评论列表(0)

  1. 暂无评论