如何获取react-native-select-dropdown选中值并保存到变量?
在React Native中使用react-native-select-dropdown保存选中的国家值
要把选中的国家值保存到变量里,直接用React的状态管理就能实现,具体操作如下:
- 引入React的
useState钩子,用来创建状态变量存储选中值 - 声明状态变量(比如
selectedCountry)和对应的更新函数 - 在
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
相关产品推荐
相关产品推荐

