React Native自定义renderItem失效问题求助
解决React Native FlatList自定义renderItem不生效的问题
你的自定义renderItem函数无法工作,核心是两个错误:
错误1:函数未返回JSX元素
你的CardFunction里编写了JSX结构,但没有通过return返回内容。箭头函数如果用大括号包裹函数体,必须显式返回值,否则默认返回undefined,导致FlatList渲染空组件。
错误2:参数解构错误
FlatList的renderItem回调接收的是包含item、index等属性的对象,不是直接传入数组的单个item。你直接用(item)接收,实际拿到的是这个包裹对象,而非数据项本身,所以item.nombre会取不到值。
修复后的完整代码
import { StyleSheet, Text, View, TouchableOpacity, FlatList } from 'react-native' import React from 'react' import Ionicons from 'react-native-vector-icons/Ionicons'; import VisitasHeader from './VisitasHeader'; const VisitasCard = ({visitas,titulo}) => { // 修复后的renderItem函数 const CardFunction = ({ item }) => { // 解构拿到真正的item数据 return ( <View style={{marginBottom:10}}> <View style={styles.card_top}> <View style={styles.holder}> <View style={styles.icon}> <Ionicons name='ios-people-circle-sharp' color='white' size={48} /> </View> <View style={styles.visitante}> <Text style={styles.text_nombre}>{item.nombre} </Text> <Text style={styles.text_cedula}>e-0000001</Text> <View> <Text style={styles.text_fecha}>2 de enero de 2022</Text> </View> </View> </View> </View> <View style={styles.card_bottom}> <TouchableOpacity style={styles.button_accept}> <Text style={styles.button_text}>Aceptar</Text> </TouchableOpacity> <TouchableOpacity style={styles.button_reject}> <Text style={styles.button_text}>Rechazar</Text> </TouchableOpacity> </View> </View> ) } return ( <FlatList ListHeaderComponent={<VisitasHeader title={titulo} />} data={visitas} keyExtractor={item => item.id} renderItem={CardFunction} ListEmptyComponent={<Text style={{textAlign:'center',paddingTop:10}}>No tiene visitas por aprobar.</Text>} /> ) } export default VisitasCard const styles = StyleSheet.create({ button_accept:{ backgroundColor:'green', padding:10, borderRadius:12, }, button_text:{ color:'white', fontWeight:'bold', }, button_reject:{ backgroundColor:'red', padding:10, borderRadius:12, }, card_bottom:{ height:50, flexDirection:'row', alignItems:'center', justifyContent:'center', borderWidth:1, borderColor:'#3959ea', borderBottomLeftRadius:8, borderBottomRightRadius:8, justifyContent:'space-evenly' }, card_top:{ height:100, backgroundColor:'#3959ea', borderTopLeftRadius:8, borderTopRightRadius:8, alignItems:'center', justifyContent:'center', }, holder:{ flexDirection:'row', }, icon:{ padding:10, alignItems:'center', margin:12, }, text_cedula:{ color:'white', fontSize:18, textTransform:'uppercase', fontWeight:'600', }, text_nombre:{ color:'white', fontSize:24, textTransform:'capitalize', fontWeight:'800', }, text_fecha:{ color:'white' }, visitante:{ flex:2, justifyContent:'center', alignItems:'flex-start', } })
额外说明
- 你注释的简单renderItem能工作,是因为它用了
({item})解构参数,并且箭头函数用了隐式返回(没有大括号,直接返回JSX) - 也可以把
CardFunction改成隐式返回的写法,省略return:const CardFunction = ({ item }) => ( <View style={{marginBottom:10}}> {/* 剩余JSX结构 */} </View> )
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

