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

如何获取react-native-select-dropdown选中值并保存到变量?

在React Native中使用react-native-select-dropdown保存选中的国家值

要把选中的国家值保存到变量里,直接用React的状态管理就能实现,具体操作如下:

  1. 引入React的useState钩子,用来创建状态变量存储选中值
  2. 声明状态变量(比如selectedCountry)和对应的更新函数
  3. 在onSelect回调里调用更新函数,把选中的项存入状态变量

修改后的完整代码示例:

import React, { useState } from 'react';
import SelectDropdown from 'react-native-select-dropdown';

const YourComponent = () => {
  const countries = ["Egypt", "Canada", "Australia", "Ireland"];
  // 声明状态变量,初始值可设为null或默认选中的国家
  const [selectedCountry, setSelectedCountry] = useState(null);

  return (
    <SelectDropdown
      data={countries}
      onSelect={(selectedItem, index) => {
        console.log(selectedItem, index);
        // 将选中的国家保存到状态变量
        setSelectedCountry(selectedItem);
      }}
      buttonTextAfterSelection={(selectedItem, index) => {
        return selectedItem;
      }}
      rowTextForSelection={(item, index) => {       
        return item;
      }}
    />
  );
};

export default YourComponent;

之后你就可以在组件的任意位置使用selectedCountry变量了——比如用于条件渲染、传递给子组件,或者提交表单时获取选中值。

内容的提问来源于stack exchange,提问作者Pablo Ortiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:14:52