Using 'ref' as array in React

落爺英雄遲暮 提交于 2021-02-09 08:01:28

问题


I have some issues when im trying to reference inputs as arrays in React with Redux.

The code below maps one Panel per article in the array.

var articles = this.props.item.array.articles.map((article, index) => {
     return <Panel key={index} header={'Article ' + index}>
        <Input type='select' ref='id' label='Article' defaultValue={article.id} >
          {articles}
        </Input>
     </Panel>
})

I'm trying to construct the refs so that they're in an array format, which does not seem to be possible at the moment. Array of references. #1899

I guess i could solve this by create some sort of ref="article["+counter+"][id]"

But that is a horrible solution, and i really don't want to go down that path.

The json array below would be my desired format for the refs:

"articles": [
        {
            "_joinData": {
                "price": "100",
                "quantity": "50"
            },
            "id": "05f54207-fb6f-40b5-820e-26059a803343"
        },
        {
            "_joinData": {
                "price": "200",
                "quantity": "70"
            },
            "id": "05f54207-fb6f-40b5-820e-26059a803343"
        }
]

The price & quantity index would be 2 more inputs.

Which i've decided to not include in the code example.

A nice solution to this problem would be very appreciated.


回答1:


I believe you can iterate through this.refs like an array by using Object.keys.

Ex. Object.keys(this.refs).forEach(key => func(this.refs[key]))

To run func function for each reference.



来源:https://stackoverflow.com/questions/35317082/using-ref-as-array-in-react

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!