You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用React Hook Form获取SelectDropdown选中值的问题

解决React Hook Form配合react-native-select-dropdown获取选中值的问题

核心问题是你没把SelectDropdown的选中值同步到React Hook Form的表单状态里,只需两步就能搞定:

1. 在onSelect回调中同步表单值

在SelectDropdown的onSelect方法里,调用React Hook Form提供的onChange函数,把选中的项(或你需要的字段,比如selectedItem.id)传递进去,这样表单就能捕获到选中值。

2. 同步组件的初始选中状态

因为这个组件没有value属性,我们可以用它的defaultValue属性,绑定Controller的field.value,让组件显示的选中状态和表单值保持一致。

修改后的完整代码:

import SelectDropdown from 'react-native-select-dropdown'
import { Control, Controller } from 'react-hook-form'
// 假设已导入Text、View、FontAwesome等所需组件

<Controller
  name={name}
  control={control}
  rules={{
    required: required,
  }}
  // 可根据需求设置初始值,比如默认选中项或null
  initialValue={null}
  render={({ field: { value, onChange } }) => {
    return (
      <>
        {label && (
          <Text className="text-black text-sm mb-1">
            {label}
          </Text>
        )}
        <SelectDropdown
          data={data}
          // 关键:选中后调用onChange同步到表单
          onSelect={(selectedItem, index) => {
            console.log(selectedItem.id)
            // 可传递整个选中对象,也可只传id,按需选择
            onChange(selectedItem)
            // 若只需id则改为 onChange(selectedItem.id)
          }}
          // 绑定defaultValue,让组件显示当前表单的选中值
          defaultValue={value}
          renderDropdownIcon={isOpened => {
            return <FontAwesome
              name={isOpened ? 'chevron-up' : 'chevron-down'}
              color={theme.colors.azul}
              size={12}
            />;
          }}
          renderCustomizedRowChild={(item, index) => {
            return (
              <View className="ml-5">
                <Text>{item?.quantidade}</Text>
              </View>
            );
          }}
          buttonTextAfterSelection={(selectedItem, index) => {
            return selectedItem.quantidade;
          }}
          defaultButtonText={'Seleçõe uma opção'}
          buttonStyle={{
            width: '100%',
            height: 30,
            backgroundColor: '#FFF',
            borderRadius: 8,
            borderWidth: 1,
            borderColor: theme.colors.azul
          }}
          buttonTextStyle={{
            color: '#444',
            textAlign: 'left',
            fontSize:14,
            fontFamily:theme.fonts.MontserratMedium
          }}
        />
      </>
    )
  }}
/>

额外说明:

  • 表单提交时,可通过getValues(name)或handleSubmit的回调参数直接获取选中值。
  • 若需要默认选中某个选项,将initialValue设置为对应的数据项即可,比如initialValue={data[0]}。

内容的提问来源于stack exchange,提问作者Jorge Edo. Hernandez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 02:55:20