首页 > 解决方案 > 在反应中循环遍历数组并将它们添加到选择选项

问题描述

在此处输入图像描述我需要帮助解决我面临的这个问题......所以我试图遍历一系列国家并将其放入我的选择表单中,但我遇到的问题是当我尝试在下拉菜单中选择项目时出现错误。 . 这是代码。

// an array of country names
const countryNames = getNames();
// example output
["united states", "united kingdom", "syria", "spain", "mexico"]
//state
const [country, setCountry] = useState("");
function handleCountry({target}){
setCountry(target.value)
}

//the form
<select name="country" value={country} onChange={handleCountry}>
{countryNames.map((country) => {
  return <option value={country}>{country}</option>
})}
</select>

当我点击浏览器上的表格时,我可以在下拉列表中看到名称,但如果我选择一个国家,我会收到错误消息……我知道这可能是一个愚蠢的问题,但我有点需要帮助,哈哈。基本上我的问题是如何将选定的选项传递给我的 onChange 函数。谢谢!

标签: javascriptarraysreactjs

解决方案


尝试这个

function handleCountry(country, index){
  setCountry(target.value)
}

<select name="country" value={country} onChange={handleCountry}>
  {countryNames.map((country, i) => {
    return <option key={i} value={country} onSelect={() => handleCountry(country,i)}>{country}</option>
  })}
</select>

推荐阅读