You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中FlatList不显示TextInput输入的新增项问题排查

修复方案

核心问题

renderItem函数未显式返回JSX元素。箭头函数使用花括号{}包裹函数体时,必须手动书写return语句返回要渲染的内容,否则默认返回undefined,FlatList识别为空内容,因此新增条目后无法渲染。

修复代码

你可以选择两种方式修改renderItem:

方式1:添加return语句

const renderItem = ( {item} ) => {
  return (
    <View style={{backgroundColor:'#6b4d87', marginVertical: 10, flexDirection:'row', alignItems:'center', justifyContent:'space-between', height:60, width:'95%', borderRadius:10 }}>
      <View>
        <Text style={{color:'black', fontSize:20, fontWeight:'bold'}}>{item.text}</Text>
      </View>

      <TouchableOpacity onPress={() => deleteHandler(item.id)}>
        <TrashIcon size={35} name="trash" style={{color:'#eff9f0'}} />
      </TouchableOpacity>
    </View>
  );
};

方式2:使用箭头函数隐式返回(去掉花括号改用圆括号包裹)

const renderItem = ( {item} ) => (
  <View style={{backgroundColor:'#6b4d87', marginVertical: 10, flexDirection:'row', alignItems:'center', justifyContent:'space-between', height:60, width:'95%', borderRadius:10 }}>
    <View>
      <Text style={{color:'black', fontSize:20, fontWeight:'bold'}}>{item.text}</Text>
    </View>

    <TouchableOpacity onPress={() => deleteHandler(item.id)}>
      <TrashIcon size={35} name="trash" style={{color:'#eff9f0'}} />
    </TouchableOpacity>
  </View>
);

可选优化项

为避免后续出现其他渲染异常,可同步调整以下内容:

  • 给包裹FlatList的外层View添加flex:1样式,确保列表高度计算正确,同时将keyExtractor返回的id转为字符串,符合React对key类型的推荐要求:
<View style={{alignItems:'center', flex: 1}}>
  <FlatList
    data={todos}
    renderItem={renderItem}
    keyExtractor={item => item.id.toString()}
  />
</View>
  • 替换随机id生成逻辑为时间戳,避免随机数重复导致的key冲突:
const newTodo = {
  id: Date.now(),
  text: userInput,
  completed: false,
};

内容的提问来源于stack exchange,提问作者Muditha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:15:04