React Native中选中表格行并传递数据至另一页面表格问题
问题:跳转页面传递选中行数据时显示undefined
点击FlatList中的表格行后,尝试将该行数据传递到目标页面,但在目标页面用console.log()打印传递的数据时,结果显示为undefined。相关代码如下:
const SelectedRow=()=>{ return navigation.navigate("CariHesapListesiDetayli",{selectedRow:response.Hareketler.filter(item=>item.Kodu===kod)} ) }
<FlatList data={filteredData} numColumns={1} style={{width: '100%'}} keyExtractor={(item, index) => index + ''} ListHeaderComponent={tableHeader} stickyHeaderIndices={[0]} renderItem={({item, index}) => { return ( <TouchableOpacity style={{ ...styles.tableRow, backgroundColor: index % 2 == 1 ? 'gray' : '#e5e5e5', }} onPress={SelectedRow}> <Text style={styles.columnRowTxt}>{index+1}</Text> <Text style={styles.columnRowTxt}>{item.Adi}</Text> <Text style={styles.columnRowTxt}>{item.Kodu}</Text> <Text style={styles.columnRowTxt}>{item.Bakiye}</Text> </TouchableOpacity> ); }} />
问题原因
SelectedRow函数没有接收当前点击行的item参数,内部无法获取选中行的Kodu值,导致过滤逻辑失效,传递的数据为空或错误。onPress直接绑定SelectedRow函数,没有将当前行的item传入,函数拿不到选中行的任何信息。
修复方案
修改SelectedRow为接收item参数的函数,并在点击时传入当前行数据:
// 接收当前点击的item参数 const SelectedRow = (item) => { // 直接传递选中的行数据,若需过滤则基于当前item的Kodu navigation.navigate("CariHesapListesiDetayli", { selectedRow: item }); }
更新FlatList的TouchableOpacity的onPress绑定:
<TouchableOpacity style={{ ...styles.tableRow, backgroundColor: index % 2 == 1 ? 'gray' : '#e5e5e5', }} // 调用时传入当前行的item onPress={() => SelectedRow(item)} > <Text style={styles.columnRowTxt}>{index+1}</Text> <Text style={styles.columnRowTxt}>{item.Adi}</Text> <Text style={styles.columnRowTxt}>{item.Kodu}</Text> <Text style={styles.columnRowTxt}>{item.Bakiye}</Text> </TouchableOpacity>
可选:保留过滤逻辑的写法
如果业务上必须通过response.Hareketler过滤数据,确保使用当前行的Kodu:
const SelectedRow = (item) => { const targetRows = response.Hareketler.filter(h => h.Kodu === item.Kodu); navigation.navigate("CariHesapListesiDetayli", { selectedRow: targetRows }); }
内容的提问来源于stack exchange,提问作者ebrua
相关产品推荐
相关产品推荐

