게임화면3 코드 정리

순9·2024년 2월 14일

react고양이게임

목록 보기
14/14

기존코드

 const animateImage = (
    index: number,
    keyframes: KeyframeType[],
    options: AnimationType
  ) => {
    const imgRout = `#imgMove${index}`;
    const blockImg = document.querySelector(imgRout);
    blockImg?.animate(keyframes, options);

  };
 <img       key={index}
            id={`imgMove${index}`}
            src={item}
            alt="고양이 이미지"
            // style={{ opacity: "0" }}
          />

document.querySelector 사용 해당 id값 대로 애니메이션이 적용 되도록 함
문제 사항
DOM을 직접적으로 접근하는 거여서 UseRef를 사용 하는 것으로 수정

수정1

const imgRefs = useRef<HTMLImageElement>(null);

 const animateImage = (
    index: number,
    keyframes: KeyframeType[],
    options: AnimationType
  ) => {
    const imgRout = `#imgMove${index}`;
     
    const blockImg2 = imgRefs;
    const blockImg3 = imgRefs.current;
    const blockImg4 = imgRefs.current!.id;
    const blockImg5 = imgRefs.current.querySelector(`#${blockImg4}`);
    blockImg3?.animate(keyframes, options);

    console.log(blockImg); //도큐멘트 사용
    console.log(blockImg2); //돔 참조인 값
    console.log(blockImg3); //참조 값 다 출력
    console.log(`#${blockImg4}`); //divImgMove.current!.id;
    console.log(blockImg5); // null
  };
 <img       ref={imgRefs}
            key={index}
            id={`imgMove${index}`}
            src={item}
            alt="고양이 이미지"
            // style={{ opacity: "0" }}
          />
  1. ref초기값, img태그에 참조값 작성
  2. imgRefs.current 값 나오는지 확인
  3. imgRefs.current.querySelector(#${blockImg4}); 해당 id 값 나오는지 확인
    콘솔은 다 정상적으로 나옴 blockImg5만 제외 하고
    querySelector 메서드는 document 객체에 직접 사용
    React의 Ref 객체이므로 일반적으로 DOM 요소가 아닐 수 있어서 null 값이 나옴 (현재 내코드에서는 DOM 아닌건가)
  4. 콘솔에는 참조된 값이 정상적으로 나옴 문제는 애니메이션이 적용이 안됨

수정2

type KeyframeType = {
  [key: string]: string | number; 
};


const imgRefs = useRef<Array<HTMLImageElement | null>>([]);



const animateImage = (
    index: number,
    keyframes: KeyframeType[],
    options: AnimationType
  ) => {
    const imgRout = `#imgMove${index}`;
    
    if (imgRefs.current && imgRefs.current[index]) {
      const blockImg3 = imgRefs.current[index];
      const blockImg5 = imgRefs.current[index]?.querySelector(imgRout);
      blockImg3?.animate(keyframes, options);
      console.log(blockImg3); // 참조 값 다 출력
    } else {
      console.log("imgRefs.current is null or undefined");
    }
  };


const startAnimation = () => {
    imgUrl.forEach((i, index) => {
      const ramdom = Math.floor(Math.random() * 5);
      const keyframes = [
        { opacity: 0.9, transform: `translateX(${ramdom * 10}px)` },
        { opacity: 1, transform: `translate(${ramdom * 10}px, 500px)` },
      ];

      const options: AnimationType = {
        delay: 2000 * (ramdom + 1), //몇초동안 대기 후 시작
        duration: 1000 * stepValue, //몇초동안 지속
        easing: "ease-in", //감속 조절
        iterations: 1, //반복 횟수
      };

      animateImage(index, keyframes, options);
    });
  };
  useEffect(() => {
    startAnimation();
  }, [imgUrl]);


{imgUrl.map((item, index) => (
           <div key={index} className="imgBox_div" onClick={() => handleImgClick(index)} ref={(ref) => (imgDivRefs.current[index] = ref)}>
            <img
             ref={(element) => imgRefs.current[index] = element}
            key={index}
            id={`imgMove${index}`}
            src={item}
            alt="고양이 이미지"
            style={{ opacity: "0" }}
          />
          </div>
         
        ))}
  1. 참조 값을 리스트에 저장 하기위해 빈 배열로 작성 배열을 통해 이미지 요소들을 조작하거나 접근
  2. 파이어베이스에서 가져오는 데이터에 img 태그로 이미지 출력
  • (element)는 React에 의해 자동으로 제공되는 매개변수
  • (element) => imgRefs.current[index] = element은 화살표 함수로, 이미지 요소에 대한 참조가 함수의 매개변수 element로 전달
  • imgRefs.current는 useRef를 통해 생성한 객체의 속성 중 이고 배열
  • 이미지 요소가 렌더링될 때마다 해당 요소에 대한 참조가 imgRefs.current 배열의 인덱스 위치에 저장
  1. type KeyframeType 애니메이션 관련 타입
    4.startAnimation 함수안에서 animateImage함수가 받을 파라미터 받고 함수 실행
  2. animateImage 각각 이미지를 animate에 넘겨 애니메이션 적용

어렵다..

profile
1. 사용법 익히기 2. 원리가 뭔지 찾아보기 3. 원리를 공부하기

0개의 댓글