개발자
안녕하세요. 질문이 있습니다! 현재 dynamic import 와 forwardRef를 사용하는 과정에서 forwardRef가 적용이 안되는 상황입니다. Canvas 컴포넌트에서는 ref값이 제대로 출력이 되는데 dynamic import와 forwardRef를 사용해 부모 컴포넌트 (DrawingPage)에서 ref값을 콘솔에 찍어보니 전달이 안됩니다. 정보를 찾아보고 수정을 해봐도 오랫동안 제자리 걸음이라 질문남깁니다! 하단은 코드입니다
답변 1
ref는 prop으로 넘길 수 없어 forwardRef를 통해 ref prop으로 전달이 가능하도록 합니다. 코드 상에 forwardRef로 감싸 ref를 prop으로 전달받은 ForwardFabricCanvas에서 다음 컴포넌트로 넘기는 경우 forwardRef={ref} 로 넘겨 주시고, FabricCanvas 컴포넌트에서는 forwardRef 를 제거하고 props로서 forwardRef를 props로 전달받아 canvas에 전달해 주시면 될 거 같습니다. 아래 코드처럼 시도해 보시면 좋겠습니다!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
DrawingPage.tsx const FabricCanvasWithNoSSR = dynamic( () => import('@/src/components/FabricCanvas'), { ssr: false, loading: () => <LoadingSpinner />, }, ); const ForwardFabricCanvas = forwardRef((props: any, ref: any) => { console.log('ref: ', ref); return <FabricCanvasWithNoSSR {...props} forwardRef={ref} />; }); export default function DrawingPage() { const canvasRef = useRef<HTMLCanvasElement>(null); const onClick = () => { if (canvasRef.current) { const data = canvasRef.current.toDataURL(); console.log(data); } else { console.log('not initialized yet.'); } }; useEffect(() => { if (canvasRef.current) { console.log('now set:', canvasRef.current); } else { console.log('not set'); } }, [canvasRef.current]); return ( <ForwardFabricCanvas ref={canvasRef} /> ); }; ------------ Canvas.tsx const FabricCanvas = ({ forwardRef }: { forwardRef: ForwardedRef<HTMLCanvasElement> }) => { const canvasRef = useRef<HTMLCanvasElement>(null); const canvasInstance = useRef<fabric.Canvas | null>(null); useImperativeHandle(forwardRef, () => ({ getCanvas: () => canvasRef.current, })); return ( <canvas ref={canvasRef} id="canvas" width={350} height={407} className=" rounded-lg" /> }); export default FabricCanvas;
익명
작성자
2024년 05월 05일
수정을 해보니 아직 null값이 들어오긴 하지만 해결하는 것에 있어서 한발 다가간 느낌입니다. 답변 정말 감사합니다!!
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
지금 가입하면 모든 질문의 답변을 볼 수 있어요!