React Native中如何在onSubmit时获取并存储所有TextInput值
问题解决:将所有赛事的比分输入存储到指定格式的数组中
核心问题分析
你的代码存在几个关键问题导致无法正确存储所有输入值:
- 自定义的
this.state1不是React的状态变量,React不会追踪它的变化,修改后不会触发组件更新,也无法正确保存数据 handleChange方法没有关联具体的赛事ID,无法区分不同赛事的输入TextInput的value绑定错误,所有输入框都绑定到同一个值,无法独立存储每个赛事的比分matchscores的初始化结构不符合需求,没有包含matchId
修正后的完整代码
import React from 'react'; import { StyleSheet, Text, View as SafeAreaView, Button, Alert } from 'react-native'; import { styles } from './stylesheet'; import { TextInput } from 'react-native-web'; export default class FetchSoccerMatches extends React.Component { state = { loading: true, matches: [], // 用对象存储比分,key为matchId,value为包含homeScore和awayScore的对象 matchscores: {} }; // 修改handleChange,接收matchId和比分类型(home/away) handleChange = (matchId, type, value) => { this.setState(prevState => ({ matchscores: { ...prevState.matchscores, [matchId]: { // 保留已有数据,只更新当前修改的比分 ...prevState.matchscores[matchId], [type]: value } } })); }; handleSubmit = () => { // 将matchscores对象转换为要求的数组格式 const formattedScores = Object.entries(this.state.matchscores).map(([matchId, scores]) => ({ matchId: parseInt(matchId), homeScore: scores.homeScore || 0, awayScore: scores.awayScore || 0 })); console.log('提交的比分数据:', formattedScores); // 这里可以添加提交到后端的逻辑 }; async componentDidMount() { const options = { method: 'GET', headers: { 'X-RapidAPI-Key': '1ee01fa5e8msh6746fc88b24d9f6p18d6e0jsn1d11e8f67917', 'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com' } }; try { const response = await fetch('https://api-football-v1.p.rapidapi.com/v3/fixtures?league=39&season=2022&round=Regular Season - 7', options); const data = await response.json(); const myMatches = data.response; this.setState({ matches: myMatches, loading: false }); } catch (err) { console.error(err); this.setState({ loading: false }); } } render() { if (this.state.loading) { return <SafeAreaView><Text>loading...</Text></SafeAreaView>; } if (!this.state.matches.length) { return <SafeAreaView><Text>没有获取到赛事数据</Text></SafeAreaView>; } return ( <SafeAreaView> <Text style={styles.h2Style}>Place a bet</Text> {this.state.matches.map(match => { // 获取当前赛事已输入的比分,默认空字符串 const currentScores = this.state.matchscores[match.fixture.id] || { homeScore: '', awayScore: '' }; return ( <SafeAreaView key={match.fixture.id} style={styles.paragraphHomePage}> <Text style={styles.testing}> <Text style={styles.teamNames}>{match.teams.home.name}</Text> <Text style={styles.vs}>-</Text> <Text style={styles.teamNames}>{match.teams.away.name} {'\n'}</Text> <TextInput style={styles.textInputStyle} placeholder="Tore " placeholderTextColor="#d3d3d3" keyboardType={'numeric'} value={currentScores.homeScore} onChangeText={(value) => this.handleChange(match.fixture.id, 'homeScore', value)} /> <Text style={styles.vs}>-</Text> <TextInput style={styles.textInputStyle} placeholder="Tore" placeholderTextColor="#d3d3d3" keyboardType={'numeric'} value={currentScores.awayScore} onChangeText={(value) => this.handleChange(match.fixture.id, 'awayScore', value)} /> </Text> </SafeAreaView> ); })} <SafeAreaView> <Button title="Press me" style={styles.placebetbutton} onPress={this.handleSubmit} /> </SafeAreaView> </SafeAreaView> ); } }
关键修改点说明
- 统一状态管理:把
matchscores移到React的state中,确保React能追踪其变化 - 比分存储结构:用对象存储比分,以赛事ID作为key,这样可以快速定位到具体赛事的比分数据
- 修改handleChange:新增
matchId和type参数,明确知道要更新哪个赛事的哪项比分,同时使用函数式更新setState确保获取最新的状态 - 绑定TextInput值:每个输入框绑定对应赛事的比分,实现独立存储
- 格式化提交数据:在
handleSubmit中把对象格式的比分转换为你需要的数组格式,确保每个项包含matchId、homeScore和awayScore
内容的提问来源于stack exchange,提问作者Marino Ivakovic
相关产品推荐
相关产品推荐

