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

React Native列表新增项显示undefined问题求助

问题分析与修复方案

你的代码里有两个关键错误导致新增项的字段显示undefined,还有一个潜在的函数未定义问题,具体修复如下:

1. 输入框事件绑定错误

第二个描述输入框用了onChange,但React Native的TextInput需要用onChangeText来直接获取输入文本。onChange返回的是事件对象,不是用户输入的内容,所以descriptionItem状态一直没拿到正确值。

修复后的输入框代码:

<TextInput 
  style={styles.input} 
  placeholder={'Write a name'} 
  value={recipeName} 
  onChangeText={(text) => setRecipeName(text)} 
/>
<TextInput 
  style={styles.input} 
  placeholder={'Write a date'} 
  value={descriptionItem} 
  onChangeText={(text) => setDescriptionItem(text)} // 替换为onChangeText
/>

2. 新项属性名不匹配

创建新项时,你给描述字段起名descriptionItem,但初始数据和渲染列表时用的都是description字段,导致渲染时找不到对应值。

修复后的handleAddButtonClick函数:

const handleAddButtonClick = () => {
  const newItem = {
    itemName: recipeName,
    description: descriptionItem, // 属性名改为description
    id: items.length
  };
  console.log(newItem);
  const newItems = [...items, newItem];
  setItems(newItems);
  // 清空输入框,提升用户体验
  setRecipeName("");
  setDescriptionItem("");
};

3. 潜在问题:未定义的函数

列表项的onPress绑定了completeTask(index),但这个函数从未定义,点击会触发报错。如果不需要这个功能可以直接移除绑定,或者补充函数定义:

// 示例:补充completeTask函数(实现删除项逻辑)
const completeTask = (index) => {
  const updatedItems = [...items];
  updatedItems.splice(index, 1);
  setItems(updatedItems);
};

把这些修改应用到代码后,新增项就能正确显示输入的名称和描述了。

内容的提问来源于stack exchange,提问作者User G Amsterdam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:35:41