[英]Set default value of dropdown in React
I have an array like [ {code: 'in', name: 'India' }, ...] for all countries and rendered a dropdown list with all countries as option
using map
.我有一个像 [ {code: 'in', name: 'India' }, ...] 这样的数组,用于所有国家,并使用
map
呈现了一个包含所有国家的下拉列表作为option
。 I want to set India as default value when the component renders but I always get Argentina as default option because it is first on the array.我想在组件呈现时将 India 设置为默认值,但我总是将 Argentina 作为默认选项,因为它在数组中是第一个。 Please suggest me a way to achieve it.
请建议我实现它的方法。 I tried finding answers but those are not working or may be I'm doing something wrong.
我尝试寻找答案,但这些都不起作用,或者可能是我做错了什么。 Here is the code required:
这是所需的代码:
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
has an attribute called "selected", which is a boolean setting. option
有一个名为“selected”的属性,它是一个 boolean 设置。
So you can do this -所以你可以这样做 -
<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>
Let me know if this works out for you.让我知道这是否适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.