React Native中如何通过API发送多数组请求体并绑定单选按钮值
React Native实现多数组API请求体并绑定单选按钮值
核心实现步骤
1. 状态管理
用useState分别管理单选按钮的选中值,以及请求体中items数组的内容:
import { useState } from 'react'; import { View, Text, TouchableOpacity, Button } from 'react-native'; export default function App() { // 单选按钮值:1代表"是",0代表"否",直接映射到categories[0].value const [radioValue, setRadioValue] = useState(1); // 模拟items数组,可根据实际需求动态修改 const [items, setItems] = useState([ { id: 1, name: "Item 1", value: "示例值1" }, { id: 2, name: "Item 2", value: "示例值2" } ]);
2. 单选按钮绑定与样式
通过TouchableOpacity实现单选按钮,点击时更新radioValue,并通过样式区分选中状态:
// 单选按钮组 return ( <View style={{ padding: 20, gap: 15 }}> <View style={{ flexDirection: 'row', gap: 20 }}> <TouchableOpacity onPress={() => setRadioValue(1)} style={{ flexDirection: 'row', alignItems: 'center', padding: 8, borderWidth: radioValue === 1 ? 2 : 1, borderColor: radioValue === 1 ? '#2196F3' : '#ccc', borderRadius: 4, }} > <View style={{ width: 20, height: 20, borderRadius: 10, backgroundColor: radioValue === 1 ? '#2196F3' : 'transparent', borderWidth: 1, borderColor: '#ccc', marginRight: 8, }} /> <Text>是</Text> </TouchableOpacity> <TouchableOpacity onPress={() => setRadioValue(0)} style={{ flexDirection: 'row', alignItems: 'center', padding: 8, borderWidth: radioValue === 0 ? 2 : 1, borderColor: radioValue === 0 ? '#2196F3' : '#ccc', borderRadius: 4, }} > <View style={{ width: 20, height: 20, borderRadius: 10, backgroundColor: radioValue === 0 ? '#2196F3' : 'transparent', borderWidth: 1, borderColor: '#ccc', marginRight: 8, }} /> <Text>否</Text> </TouchableOpacity> </View>
3. 构造目标格式的请求体
编写函数将状态整合成你需要的多数组结构:
// 构造API请求体 const buildRequestBody = () => { return { items: items, categories: [ { value: radioValue, // 可添加categories数组的其他字段,如id、name等 } ] }; };
4. 发送API请求
用fetch发送POST请求,携带构造好的请求体:
// 发送API请求 const sendApiRequest = async () => { const requestBody = buildRequestBody(); try { const response = await fetch('你的实际API地址', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(requestBody), }); const result = await response.json(); console.log('请求成功:', result); // 可添加成功后的提示逻辑,如Alert弹窗 } catch (error) { console.error('请求失败:', error); // 处理错误逻辑 } }; // 发送请求按钮 <Button title="提交请求" onPress={sendApiRequest} /> </View> ); }
注意事项
- 根据实际业务需求,修改
items数组的内容,或添加动态增删item的逻辑。 - 将代码中的
你的实际API地址替换为真实接口地址。 - 可优化错误处理,比如用
Alert组件向用户展示请求结果。
内容的提问来源于stack exchange,提问作者Muhammd Abdullah
相关产品推荐
相关产品推荐

