reactjs - 在 React 中设置下拉菜单的默认值
问题描述
我有一个数组,如 [ {code: 'in', name: 'India' }, ...] 用于所有国家,并呈现一个下拉列表,所有国家都option
使用map
. 我想在组件渲染时将 India 设置为默认值,但我总是将 Argentina 作为默认选项,因为它在数组中是第一个。请建议我实现它的方法。我试图找到答案,但这些都不起作用,或者可能是我做错了什么。这是所需的代码:
export default function NavBar({ setUserSearch, country, setCountry }) {
const handleCountryChange = (e) => {
setCountry({code: e.target.value, name: e.target.innerText})
}
return (
<select className="country_dropdown mx-3 py-1 px-1 text-dark" onChange = {handleCountryChange}>
{countries.map(country => {
return <option value = {country.code} key = {country.code}>{country.name}
</option>
}
)
}
</select>
)
}
解决方案
option
有一个名为“selected”的属性,它是一个布尔设置。
所以你可以这样做 -
<select className="country_dropdown mx-3 py-1 px-1 text-dark" onChange = {handleClick}>
{countries.map(country => {
return <option value={country.code} key={country.code} selected={country.code === 'in'}>
{country.name}
</option>
})}
</select>
让我知道这是否适合您。
推荐阅读
- javascript - 在 xrange 图表的 Highstocks 版本中不支持 x 轴上的最小值/最大值
- mocha.js - sinon fake server.requests 返回一个空数组
- c - 编译时错误为“需要左值”,但不确定原因
- python - 将蓝牙名称更改为 Pi Zero 上的当前 IP 地址
- python-3.x - 如何在 Python 中创建宏?
- sql - 如何通过语句在分区上向行号添加条件
- php - 如何更改 Laravel Passport 中 OAuthServerException 上无效凭据的默认消息?
- java - PreparedStatement 与调用 execute() 的记录不匹配
- nix - 如何将表达式实例化为 json 字符串并在此字符串中构建/实现它的所有依赖项/包
- c - 无法通过系统()从程序中设置带有“回声”的文件