[英]React JS multi-country state dropdown menu
I am trying to map over an array to create a dropdown menu with multiple countries and their associated states.我正在尝试通过数组 map 创建一个包含多个国家及其相关州的下拉菜单。 My array looks like the following (short version to save time/length):
我的数组如下所示(节省时间/长度的简短版本):
[
{
"country" : "USA",
"states" : {
"name" : ["Alabama", "Alaska"],
"value" : ["AL", "AK"]
}
},
{
"country" : "Mexico",
"states" : {
"name" : ["Aguascalientes", "Baja California"],
"value" : ["AG", "BC"]
}
}
]
and I tried to do the following:我尝试执行以下操作:
import React from 'react';
import data from './allstates.json';
const StateDrop = () => {
return (
<div >
<select>
{data.map(item => (
<optgroup label={item.country}>
<option key={item.states.name} value={item.states.value}>{item.states.name}</option>
</optgroup>
))}
</select>
</div>
);
}
export default StateDrop;
But it lists all the names in one option.但它在一个选项中列出了所有名称。 I tried to use the spread operator on the names but it says that spread children are not allowing in React.
我尝试在名称上使用扩展运算符,但它说在 React 中不允许扩展子级。
I know that I could just make 3 lists of my states data and map over those arrays under their own optgroup div, but I wanted to know if there is a way to accomplish this similar to my current approach?我知道我可以在他们自己的 optgroup div 下的那些 arrays 上列出我的状态数据和 map 的 3 个列表,但我想知道是否有一种类似于我当前方法的方法来完成这个? I could find json object with nested arrays but not any solid information here or otherwise to point me in the direction of a solution.
我可以找到带有嵌套 arrays 的 json object 但没有任何可靠的信息在这里或以其他方式指向解决方案的方向。 My first thought was to throw the names into their own array using the spread operator but this didn't work.
我的第一个想法是使用扩展运算符将名称放入他们自己的数组中,但这不起作用。 Any advice would be super helpful.
任何建议都会非常有帮助。 I thought maybe I needed to have useState and add the countries/states there but I couldn't see how that was any different.
我想也许我需要有 useState 并在那里添加国家/州,但我看不出有什么不同。
Is this what you are aiming for?这是你的目标吗?
export default function App() {
return (
<div>
<select>
{data.map(item => (
<optgroup key={item.country} label={item.country}>
{item.states.name.map((x, i) => (
<option key={x} value={item.states.value[i]}>
{x}
</option>
))}
</optgroup>
))}
</select>
</div>
);
}
it assumes that within a country, the i-th value
corresponds to i-th name
though.它假定在一个国家/地区内,第 i 个
value
对应于第 i 个name
。 If you restructure your data
you can make code cleaner though: if you turn item.states
into array of objects of the form: {name, value}
, it will become easier to render options
.如果你重组你的
data
,你可以使代码更清晰:如果你把item.states
变成如下形式的对象数组: {name, value}
,它会变得更容易呈现options
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.