ChungHa Brocher_1 : 2021.04.30 React.forwardRef
Error
1) Want to apply "Intersection Observer" to 'lastElement'
2) useCallback as 'ref' to catch the 'lastelement'
3) Component Structure
- TotalPictureContainer
- SinglePicture { ref = useCallback(lastPictElementRef) }
- PictureContainer ( want to access here )
- SingleImage
Error
Error Happened
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()
If we see the structure
We are accessing the element from 'child component' ( PictureContainer )
But if we see the 'code of 'child component'
const SinglePicture = ({ Image , IsOdd = true}) => {
return (
<PictureContainer odd = {IsOdd} >
<SingleImage
src={Image.src}
alt={Image.alt}
initial='hidden'
animate='visible'
exit='exit'
odd = {IsOdd}
/>
</PictureContainer>
)
}
we can notice that ,
it is not receiving any 'ref's
What do we have to do ??
React components hide their implementation details, including their rendered output. Thus, components cannot easily access refs from their children.
But To access ref fromt children, React provides a feature called "Ref Forwarding."
Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.
So what we mean here is that ,
we have to let
PictureContainer
component to access ref to its parent component
which is
SinglePicture
So we change the code as below
const SinglePicture = forwardRef(({ Image , IsOdd = true}, ref) => {
return (
<PictureContainer odd = {IsOdd} ref = {ref}>
<SingleImage
src={Image.src}
alt={Image.alt}
initial='hidden'
animate='visible'
exit='exit'
odd = {IsOdd}
/>
</PictureContainer>
)
})
As we can see
it is receiving 'ref' as parameter
and applying it to 'chld' component
so that it can access "ref" of its parent
component
Author And Source
이 문제에 관하여(ChungHa Brocher_1 : 2021.04.30 React.forwardRef), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@dhsys112/StarWarsAPI-2021.04.30-React.forwardRef저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)