React Native获取多个RadioGroup选中单选按钮值的方法
实现方案
核心逻辑是用一个和属性组长度一致的状态数组存储选中值,数组索引和属性组的顺序一一对应,值存储对应组选中的选项索引或者完整选项对象,单选触发时只更新数组对应位置的值即可,适配任意n个属性组的场景。
- 初始化选中状态
按照属性组的数量生成默认选中数组,默认每个组选中第一个选项,和你原有代码selectedIndex={0}的默认逻辑对齐:
import { useState } from 'react'; import { View, Text } from 'react-native'; import { RadioGroup, RadioButton } from 'react-native-flexi-radio-button'; // attributes 是接口返回的属性组列表数据 const [selectedAttrs, setSelectedAttrs] = useState(() => { // 初始化长度和属性组数量一致,默认每项为0(即第一个选项选中) return attributes.map(() => 0) });
- 遍历渲染属性组,绑定选中事件
外层遍历属性组时拿到当前组的索引,给每个RadioGroup绑定对应位置的选中值,选中回调里更新状态数组对应索引位置的值即可,注意不要混用内层选项遍历的索引:
{attributes.map((attrGroup, groupIndex) => { return ( <View key={attrGroup.option.id} style={{marginBottom: 16}}> <Text style={{fontWeight: 'bold', marginBottom: 8}}>{attrGroup.option.name}</Text> <RadioGroup style={{flexDirection: 'row', gap: 12}} size={20} thickness={2} color="#144693" // 绑定当前组对应的选中索引 selectedIndex={selectedAttrs[groupIndex]} // 选中时更新对应组的选中值 onSelect={(selectedItem, selectedIndex) => { setSelectedAttrs(prev => { const newSelected = [...prev]; // 更新当前组位置的选中值,如果要存完整选项对象就赋值selectedItem newSelected[groupIndex] = selectedIndex; return newSelected; }) }} > {attrGroup.values.map((option) => ( <RadioButton key={option.products_attributes_id} value={option}> <Text style={{marginLeft: 4}}> {option.value} {Number(option.price) > 0 ? ` (${option.price_prefix}${option.price})` : ''} </Text> </RadioButton> ))} </RadioGroup> </View> ) })}
- 获取最终选中结果
状态数组selectedAttrs就是你需要的结构:数组下标对应属性组的序号,值对应该组选中的内容。如果存的是选项索引,格式就是你期望的[0] => 0、[1] => 2这类索引对应结构;如果存的是完整选项对象,可以直接读取选中项的id、价格、属性值等所有业务字段。
注意不要在onSelect回调里写
i++这类自增逻辑,会导致索引错乱;外层遍历属性组拿到的groupIndex才是对应单选组的唯一位置标识,RadioGroup和RadioButton都要加唯一key避免组件复用导致的选中状态错乱。
内容的提问来源于stack exchange,提问作者Arnold Brown
相关产品推荐
相关产品推荐

