0

我正在使用来自 reactstrap 的 CustomInput。我正在设置要选择的类型。在我的 CustomInput type="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'
  }
]
4

1 回答 1

3

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

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

该值必须是您选择的当前值。因此,如果您根据使用选择更改它,则必须通过设置它。

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

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

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

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

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

于 2021-09-07T23:29:29.623 回答