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를 사용 하는 것으로 수정
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" }}
/>
#${blockImg4}); 해당 id 값 나오는지 확인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>
))}
어렵다..