简体   繁体   English

如何将 ref 用于循环中的同一组件?

[英]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问题是它只引用最后渲染的 Dropzone,我如何在循环渲染的所有 Dropzone 组件上使用 ref through 循环

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([]) .为此,您必须使用一个引用数组,您可以将其声明为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)} /> )}
    </>
  )

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

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