javascript - 将数据从 React Native 中的数组绑定(bind)到 TextInput

标签 javascript react-native

我有一个数据数组。喜欢

product = [
  {
    name: 'item 1',
    quantity: 10,
  },
  {
    name: 'item 2',
    quantity: 12,
  },
  {
    name: 'item 3',
    quantity: 14,
  },
]

我想在 TextInput 中显示此数量字段。

那么我该如何做到这一点并管理 onChangeText 事件呢?

最佳答案

检查这个完整的示例。

import React, { Component } from "react";
import { View, TextInput } from "react-native";

export default class Example extends Component {
  state = {
    product: [
      {
        name: "item 1",
        quantity: 10
      },
      {
        name: "item 2",
        quantity: 12
      },
      {
        name: "item 3",
        quantity: 14
      }
    ]
  };

  onChangeText = ( item, text ) => {
      let updateProducts = [...this.state.product]
      let index = this.state.product.findIndex(obj => obj.name == item.name)
      updateProducts[index].quantity = text;
      this.setState({
        product: updateProducts
      })
  }

  render() {
    return (
      <View>
        {this.state.product.map(item => (
          <TextInput
            style={{ height: 40, borderWidth: 1, margin: 5, width: "80%", padding: 5 }}
            onChangeText={(text) => this.onChangeText(item, text)}
            value={item.quantity}
          />
        ))}
      </View>
    );
  }
}

希望这对您有帮助。如有疑问,请放心。

关于javascript - 将数据从 React Native 中的数组绑定(bind)到 TextInput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60649822/

相关文章:

javascript - 使用正则表达式同时匹配两个字符串模式以进行删除

reactjs - 如何以编程方式从 React Native App 发送短信?

react-native - TabNavigator 是否已弃用?

javascript - 如何在 gulp-inject 上配置 dist 文件夹的相对文件路径?

c# - 在 Javascript 中等待点击事件完成

javascript - 如何通过 javascript 动态添加 Google Maps API?

javascript - Node JS在ejs文件中加载js和css文件

android - React Native 中适用于 ios 和 Android 的自定义字体

javascript - 评估 MapboxGLManager.mapStyles

react-native - 如何在BottomTabBar react 导航中为每个选项卡使用自定义宽度?