[英]How to access the data from an array of objects by TextInput in react native
[英]Bind data in to TextInput from an array in react native
我有一组数据。 喜欢
product = [
{
name: 'item 1',
quantity: 10,
},
{
name: 'item 2',
quantity: 12,
},
{
name: 'item 3',
quantity: 14,
},
]
我想在 TextInput 中显示这个quantity
字段。
那么我该如何做到这一点并管理onChangeText
事件呢?
首先,我为您推荐您应该从本机文档中读取数组和列表,然后您应该最终阅读TextInput属性:) 这是工作示例
https://snack.expo.io/HJm8EOPr8 - 反应原生
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
product : [
{
name: 'item 1',
quantity: 10,
},
{
name: 'item 2',
quantity: 12,
},
{
name: 'item 3',
quantity: 14,
},
]
}
}
render() {
return (
<View style={styles.container}>
{this.state.product.map(item => (
<TextInput value={item.quantity} />
))}
</View>
);
}
}
检查这个完整的例子。
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>
);
}
}
希望这对你有帮助。 如有疑问,请放心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.