简体   繁体   中英

How can I use ref for the same component which is in the loop?

array.map((el,i) =>{
      return(
          <Dropzone
          ref = {ref1}
          />
      )
    })

the question is it only ref to the last rendered Dropzone, how can I use ref through loop on all Dropzone component which is render in loop

try:

  const refs = useRef([]);
  array.map((el,i) =>{
        refs.current[i] = createRef();
          return(
              <Dropzone
               ref={refs.current[i]}
              />
          )
        })

For this, you have to use an array of refs which you can declare as const refs = useRef([]) . After that, you can access individual elements as you access the elements of an array.

const Component = ({array}) => {
  
  const refs = useRef([])
  
  return (
    <>
      {array.map((el,i) => <Dropzone ref={el => (refs.current[i] = el)} /> )}
    </>
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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