如何将 ref 用于循环中的同一组件?
How can I use ref for the same component which is in the loop?
array.map((el,i) =>{
return(
<Dropzone
ref = {ref1}
/>
)
})
问题是它只引用最后渲染的 Dropzone,如何在循环渲染的所有 Dropzone 组件上使用循环引用
尝试:
const refs = useRef([]);
array.map((el,i) =>{
refs.current[i] = createRef();
return(
<Dropzone
ref={refs.current[i]}
/>
)
})
为此,您必须使用可以声明为 const refs = useRef([])
的引用数组。之后,您可以像访问数组元素一样访问单个元素。
const Component = ({array}) => {
const refs = useRef([])
return (
<>
{array.map((el,i) => <Dropzone ref={el => (refs.current[i] = el)} /> )}
</>
)
array.map((el,i) =>{
return(
<Dropzone
ref = {ref1}
/>
)
})
问题是它只引用最后渲染的 Dropzone,如何在循环渲染的所有 Dropzone 组件上使用循环引用
尝试:
const refs = useRef([]);
array.map((el,i) =>{
refs.current[i] = createRef();
return(
<Dropzone
ref={refs.current[i]}
/>
)
})
为此,您必须使用可以声明为 const refs = useRef([])
的引用数组。之后,您可以像访问数组元素一样访问单个元素。
const Component = ({array}) => {
const refs = useRef([])
return (
<>
{array.map((el,i) => <Dropzone ref={el => (refs.current[i] = el)} /> )}
</>
)