如何在 FlatList 中单击按钮时设置 TextInput 的值?

How to set the value of TextInput on button click in FlatList?

我想增加值并将其设置为 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并设置其值?

加个钩子状态终于搞明白了

解决方案:

    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>

                )}
                />