如何在 React Native 的数组中聚焦项目长度未知的 TextInput?数组中可能有更多或更少的项目来自数据库

How to focus TextInput with unknown length of items in an array in React Native? There may be more or less items in the array coming from the database

基本上我已经完成了对 TextInput 的聚焦,而项目可能会添加到购物车或来自数据库。我正在使用 useRef 挂钩,但是当我删除或添加某些项目时,出现一些错误,指出当我在购物车中删除或添加一些项目时,呈现更多或更少。

这是包含五个项目的 cartItems 数组。

[
    {
        "isAddedToCart": true,
        "product_id": "1",
        "product_name": "PIN 36MM X 18IN",
        "quantity": 0,
        "unit": undefined
    },
    {
        "isAddedToCart": true,
        "product_id": "2",
        "product_name": "APIN 42MM X 24IN",
        "quantity": 0,
        "unit": undefined
    }, {
        "isAddedToCart": true,
        "product_id": "3",
        "product_name": "PIN 24MM X 10IN",
        "quantity": 0,
        "unit": undefined
    }, {
        "isAddedToCart": true,
        "product_id": "4",
        "product_name": "RAKAB 18MM X 24IN",
        "quantity": 0,
        "unit": "2"
    }
]

这是我创建的辅助函数。


    export const inputRef = (cartItems) => {
    const inputRefs = []
    cartItems.map((item, index) => {
        if(index != (cartItems.length-1)){
            inputRefs[index] = useRef(null);
        }        
    })

    return inputRefs;
    }

这是我的文本输入

    <TextInput
    placeholder="Qty"
    placeholderTextColor="#676767"
    style={InputStyleWithoutBorder}
    onChangeText={(quantity) => inputQuantity(item.product_id, quantity, defaultUnit.default)}
    keyboardType={"numeric"}
    value={item.quantity}
    returnKeyType={inputRefs.length == index ? "done" : "next"}
    blurOnSubmit={inputRefs.length == index ? true : false}
    ref={index == 0 ? null : inputRefs[index-1]}
    onSubmitEditing={() => { 
            index == 0 || cartItems.length != index+1 ? inputRefs[index].current.focus() :null
            inputQuantity(item.product_id, item.quantity)
        }    
    }
    />

在我从购物车中添加或删除一些商品之前,它工作正常。 对焦正常。

This is the item which can be deleted or can add later from the list of items

This is the error when I delete items in the cart

This is the error when I add items in the cart

你能试试这个解决方案吗:

export const inputRef = (cartItems) => {
  const inputRefs = useRef([])
  inputRefs.current = cartItems.map((item, index) => {
     return inputRefs.current[i] ?? createRef(null);
  })

  return inputRefs;
}
export const inputRef = (cartItems) => {
    const inputRefs = []
    cartItems.map((item, index) => {
        if(index != (cartItems.length-1)){
            inputRefs[index] = createRef(null);
        }        
    })
    return inputRefs;
}

This solution is working fine.