javascript - 在反应中循环遍历数组并将它们添加到选择选项
问题描述
我需要帮助解决我面临的这个问题......所以我试图遍历一系列国家并将其放入我的选择表单中,但我遇到的问题是当我尝试在下拉菜单中选择项目时出现错误。 . 这是代码。
// 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 函数。谢谢!
解决方案
尝试这个
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>
推荐阅读
- php - 在编译时使用环境变量配置服务
- swift - Swift UICollectionview 水平单元格显示中心位置,并根据单元格选择自动移动
- java - Angular 如何知道要调用哪个 Spring Boot REST API?
- amazon-web-services - 调用 ListQueues 操作时 AccessDenied
- python-3.x - 从字典到逆字典的字典理解
- c# - 如何在 IronPython 2.7 中引用针对运行时版本“v2.0.xxx”构建的程序集?
- c# - 确定主要货币单位和小数单位之间的因子
- postgresql - 如何在不重新启动 postgres 服务器的情况下刷新停用词列表?
- java - 不能引用非静态变量
- ios - 通过 bitrise 构建的问题;通过 xcode 构建的更多问题