映射数组时如何设置 select 选项的默认值

How to set the default value of a select option when mapping over array

我正在使用来自 reactstrap 的 CustomInput。我将类型设置为 select。在我的 CustomInput type="select" 中,我正在映射数组中的选项。我需要将 select 中的默认值设置为正在映射的特定选项。例如。我喜欢默认为美国或德国,现在我正在映射一系列不同的国家。

下面是我的代码

<CustomInput
          type="select"
          id="country"
          name="country"
          className="mb-3"
          value={country.countryCode}
          onChange={handleChange}
        >
          
          {numberCountries.map(({countryCode, name}) => ( 
            <Fragment>
              <option key={countryCode} value={countryCode}>{name}</option> <--- how can i set a one of these options to be the default value rendered on the screen?
            </Fragment>
          ))}
       
        </CustomInput>

这是我映射的对象

[
{
    name: 'United States',
    countryCode: 'US'
  },
{
    name: 'Germany',
    countryCode: 'DE'
  }
]

DOM可能支持默认值,但在受控输入组件中,你必须想出

  <input value={value} onChange={onChange} />

并且该值必须是您选择的当前值。因此,如果您根据使用选择更改它,则必须通过以下方式进行设置。

  const onChange = e => {
    setValue(e.target.value)
  }

这意味着该值始终与选择同步。如果您直接使用 DOM,情况会有所不同。

好了,有了这个理解,如果你想设置一些默认的东西,你可以做。

  const [value, setValue] = useState(country.countryCode || defaultCode)

老实说,即使 DOM 提供了默认行为,您也应该想覆盖它。因为否则你最终会遇到一些奇怪的行为。