首页 > 解决方案 > 在 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>
           ) 
}

标签: reactjsreact-functional-component

解决方案


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>

让我知道这是否适合您。


推荐阅读