最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Creating refs inside a loop - Stack Overflow

programmeradmin1浏览0评论

I am trying to create multiple refs based on the length of input array.

export default function test(props) {
    const numRefs = props.data.length;
    let [refs, setRefs] = useState([]);

    for (let i = 0; i < numrefs; i++) {
        let ref = useRef(null);
        setRefs(result => [...result, ref]);
    }


    return (
        <div>
            // Then I want to return numRefs number of divs each with a ref = one of ref from refs array
            <div ref = {}></div>
        </div>
    )
} 

React doesn't allow you to have hooks inside a loop and I am getting the error ->

' React Hook "useRef" may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every ponent render'

Is it possible to achieve this?

I am trying to create multiple refs based on the length of input array.

export default function test(props) {
    const numRefs = props.data.length;
    let [refs, setRefs] = useState([]);

    for (let i = 0; i < numrefs; i++) {
        let ref = useRef(null);
        setRefs(result => [...result, ref]);
    }


    return (
        <div>
            // Then I want to return numRefs number of divs each with a ref = one of ref from refs array
            <div ref = {}></div>
        </div>
    )
} 

React doesn't allow you to have hooks inside a loop and I am getting the error ->

' React Hook "useRef" may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every ponent render'

Is it possible to achieve this?

Share Improve this question asked May 27, 2020 at 6:03 ps1234ps1234 1612 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Make use of callback approach to assigning refs within a loop. You do not need multiple instances of useRef. You can create one ref and store all refs to div within it

export default function test(props) {
    const numRefs = props.data.length;
    let [refs, setRefs] = useState([]);
    let divRef = useRef({});


    return (
        <div>
            {Array.from(new Array(20)).map((_, i) => <div ref = {ref => divRefs.current[i] = ref}></div>)}

        </div>
    )
} 
发布评论

评论列表(0)

  1. 暂无评论