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

React Native中Map函数内TextInput绑定动态值后不显示内容问题

问题修复方案

存在的问题

  • useState使用错误:声明状态数组时未调用React的useStateHook,直接将数组赋值给了解构的状态变量,状态变更不会触发组件重新渲染。
  • return换行触发JS自动分号插入规则:return后直接换行,JS会默认在return后插入分号,返回undefined,导致TextInput组件未被正确渲染。
  • TextInput的value属性类型不匹配:DeliveredQuantity是数字类型,而TextInput的value要求传入字符串,部分版本React Native无法识别数字类型的绑定值。
  • 列表渲染未加唯一key:map遍历生成组件时未给每个子项指定唯一key属性,会触发React渲染警告,极端场景下也会导致内容渲染异常。
  • 受控组件缺少更新事件:如果需要支持输入修改,TextInput作为受控组件必须搭配onChangeText事件更新绑定的状态值,否则内容无法响应输入操作。

修正后代码

import { useState } from 'react';
import { TextInput } from 'react-native';

// 正确使用useState声明状态
const [arrayList, setArrayList] = useState([
  {id:0, ExpectedQuantity:10, DeliveredQuantity:7},
  {id:1, ExpectedQuantity:19, DeliveredQuantity:9},
  {id:2, ExpectedQuantity:11, DeliveredQuantity:11},
  {id:3, ExpectedQuantity:45, DeliveredQuantity:30},
])

// 渲染列表
const renderInputList = () => {
  return arrayList.map((item, index) => {
    // return 后用括号包裹组件避免自动分号插入问题,添加key属性,value转字符串
    return (
      <TextInput
        key={item.id}
        value={String(item.DeliveredQuantity)}
        // 如需支持编辑,添加onChangeText事件更新状态
        onChangeText={(newVal) => {
          const newList = [...arrayList]
          newList[index].DeliveredQuantity = Number(newVal)
          setArrayList(newList)
        }}
      />
    )
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 14:15:04