我想增加该值并将其设置为TextInput onclick。但是有很多TextInputs和按钮,它们与FlatList中的每个项目一起动态创建。
<FlatList keyExtractor={(item, index) => item.id.toString()} data={allGroceryItems} renderItem={itemData => (
<View style={{ alignItems: 'center', }}>
//id in item.id is an object in array & addQty(id) is just an empty function for now
<TouchableOpacity style={styles.btnCount} onPress={() => addQty(itemData.item.id)}>
<Text style={{fontFamily: 'open-sans-reg', fontSize: 16}}>+</Text>
</TouchableOpacity>
<TextInput keyboardType="numeric" placeholder="0" style={styles.txtCount}/> // this is the TextInput
<TouchableOpacity style={styles.btnCount} onPress={() => deleteQty(itemData.item.id)}>
<Text style={{fontFamily: 'open-sans-reg', fontSize: 22}}>-</Text>
</TouchableOpacity>
</View>
)}
/>
因此,基本上它是一个计数器。按下+
按钮时,它会递增数字并将其设置为单击的索引的TextInput值。按下-
按钮时,它会减小数字并设置为单击的索引的TextInput值。
如何获取被单击按钮的TextInput并设置其值?
答案 0 :(得分:0)
我终于通过添加一个钩子状态解决了这个问题。
解决方案:
const [txtValue, setTxtValue] = useState([]);
const addQty = (id) => {
const dataArr = [...txtValue];
var prev = `${dataArr[id]}` == 'undefined' ? 0 : dataArr[id];
dataArr[id] = prev + 1;
setTxtValue(dataArr);
}
const deleteQty = (id) => {
const dataArr = [...txtValue];
var prev = `${dataArr[id]}` == 'undefined' ? 0 : dataArr[id];
if(prev == 0){
dataArr[id] = prev;
}else{
dataArr[id] = prev - 1;
}
setTxtValue(dataArr);
}
<FlatList keyExtractor={(item, index) => item.id.toString()} data={allGroceryItems} renderItem={itemData => (
<View style={{ alignItems: 'center', }}>//id in item.id is an object in array
<TouchableOpacity style={styles.btnCount} onPress={() => addQty(itemData.item.id)}>
<Text style={{fontFamily: 'open-sans-reg', fontSize: 16}}>+</Text>
</TouchableOpacity>
<TextInput value={`${txtValue[itemData.item.id]}`=== "undefined" ? '0' : `${txtValue[itemData.item.id]}`} keyboardType="numeric" placeholder="0" style={styles.txtCount}/> // this is the TextInput
<TouchableOpacity style={styles.btnCount} onPress={() => deleteQty(itemData.item.id)}>
<Text style={{fontFamily: 'open-sans-reg', fontSize: 22}}>-</Text>
</TouchableOpacity>
</View>
)}
/>