简体   繁体   English

React Native Hooks - 动态地创建一个引用数组

[英]React Native Hooks - dinamically create an array of refs

Introduction介绍

I have an array of data which contains objects with unique ids.我有一个数据数组,其中包含具有唯一 ID 的对象。

I am trying to create as many references as neccessary.我正在尝试根据需要创建尽可能多的参考。 For example, if the array have 4 elements then I will create 4 references.例如,如果数组有 4 个元素,那么我将创建 4 个引用。 Each reference has to be contained in an array and also, I need to associate it to the unique id of the object.每个引用都必须包含在一个数组中,而且我需要将它与对象的唯一 id 相关联。

Here is what I am trying to do in "pseudocode":这是我在“伪代码”中尝试做的事情:

Pseudocode伪代码

 data = [{id: "10i3298yfrcd", ...}, {id: "y48hfeucldnjs", ...}]

 references = data.map(({id}) => useRef(null))

Problem问题

I don't know how to associate each created reference to its respective object id (just to access the references like with an array of alphanumeric indexes, or something like this)...我不知道如何将每个创建的引用与其各自的对象 ID 相关联(只是为了访问引用,例如使用字母数字索引数组或类似的东西)...

Also, I get an error when creating the references this way:此外,以这种方式创建引用时出现错误:

React has detected a change in the order of Hooks called by %s. React 检测到 %s 调用的 Hook 顺序发生了变化。 This will lead to bugs and errors if not fixed.如果不修复,这将导致错误和错误。 For more information, read the Rules of Hooks: https://reactjs.org/docs/hooks-rules.html有关更多信息,请阅读 Hooks 规则: https : //reactjs.org/docs/hooks-rules.html

So I suppose this is not a valid form to create references dynamically.所以我想这不是动态创建引用的有效形式。

Any ideas how to do that?任何想法如何做到这一点? Thank you.谢谢你。

this is how you can create a useRef depending of data.lenght这就是您可以根据 data.lenght 创建 useRef 的方法

import { useEffect, useRef, useState } from react;

const ArrayInputs = () => {
    const inputRef = useRef([]);
    const [data, setData] = useState([]);
    
    useEffect( () => {
        let data = ['Name', 'Age', 'Gender'];
        inputRef.current = new Array(data.length);
        setData(data);
    }, []);
    
    useEffect( () => {
        //Example of using inputRef
        if(data.length !== 0) {
            inputRef.current[data.length - 1].focus();
        }
    }, [data]);
    
    return(
        <View>
            {data.map( (element, i) => <TextInput ref = {el => inputRef.current[i] = el} />)}
        </View>
    
    );

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM