У меня есть функциональный компонент - экран, и мне нужно обработать какое-то состояние. Я не хочу реорганизовывать свой код, чтобы сделать его компонентом класса, и я хотел бы использовать хуки. У меня есть компонент на экране, который отображает плоский список (от JSON) описания продукта, количества и поля для количества пользовательского ввода. В настоящее время мое состояние для всех вводимых величин связано друг с другом, поэтому при вводе числа в 1 поле это число отображается во всех полях. Как я могу отделить и сохранить состояние ввода с помощью хуков?
В Интернете много примеров использования хуков для хранения 1 порции данных, но не нескольких, и, поскольку я не знаю, сколько «продуктов» будет много времени, я не могу создать для них разные useState. , У меня лучше всего использовать 1 useState для всех полей ввода и хранить в массиве?
import React, { useState } from 'react';
import { Text, View, StyleSheet, SafeAreaView, FlatList } from 'react-native';
function InstallScreen ({navigation, route}) {
// State for the number installed component
const [quantityInstalled, setQuantityInstalled] = useState([])
const { item } = route.params;
// pulling just the product arrays from the job data and storing separately
const productData = item.products;
return (
<View style={styles.containerNine}>
<View style={styles.descriptionBoxContainer}>
<View style={styles.descriptionBox}>
<FlatList
data={ productData }
keyExtractor={item => item.id.toString()}
renderItem={({ item }) =>
<DescriptionBox
productDescription={item.description}
dueQuantity={item.quantity}
value={quantityInstalled}
onChangeText={value => setQuantityInstalled(value)}
/>
}
/>
<Text>Number installed is {quantityInstalled } </Text>
</View>
</View>
);
};
Описание Компонент
import React from 'react';
import { View, Text, StyleSheet, TextInput } from 'react-native';
const DescriptionBox = (props) => {
return (
<View style={styles.productsAllContainer}>
<View style={styles.descriptionBoxStyle}>
<Text style={styles.textStyle}>
{props.productDescription}
</Text>
</View>
<View style={styles.qtyBoxStyle}>
<Text style={styles.qtyTextStyle}>
{props.dueQuantity}
</Text>
</View>
<View>
<TextInput
style={styles.installedBoxStyle}
textAlign='center'
fontSize='18'
fontWeight='bold'
autoCapitalize="none"
autoCorrect={false}
keyboardType={'numeric'}
maxLength={5}
value={props.value}
onChangeText={props.onChangeText}
/>
</View>
</View>
);
};