【问题标题】:How to set the default value of a select option when mapping over array映射数组时如何设置选择选项的默认值
【发布时间】:2021-11-04 18:36:03
【问题描述】:

我正在使用来自 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'
  }
]

【问题讨论】:

  • 您可以在父 CustomInput 上将其设置为 value 用于动态/受控选择,或 defaultValue 用于加载初始值。

标签: javascript html reactjs reactstrap


【解决方案1】:

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

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

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

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

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

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

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

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

【讨论】:

  • 这种方法回答了我的问题。我的特殊解决方案是将初始状态设置为数组 0 索引,如下所示, const [country, setCountry] = useState(numberCountries[0]
猜你喜欢
  • 2021-11-29
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 2018-07-20
  • 2023-02-09
  • 2015-09-19
  • 2017-02-05
相关资源
最近更新 更多