고양이를 클릭시 점수가 쌓이는 게임
.block{display: block;}
.disnone {
display: none;
}
//이미지의 부모 div
.transparent_image {
opacity: 0;
}
.imgBox_div {
width: 50px;
height: 50px;
}
const handleImgClick = (index: number) => {
const blockImg = document.querySelector(".block");
blockImg?.classList.remove("block");
blockImg?.classList.add("disnone");
SetScore(prevScore + 1);
}
{imgUrl.map((item, index) => (
<img
key={index}
id={`imgMove${index}`}
className="block"
src={item}
alt="고양이 이미지"
onClick={() => handleImgClick(index)}
style={{ opacity: "0" }}
/>
))}
이미지를 클릭시 block 클래스 제거 disnone 클래스 추가 해서 이미지가
사라지고 점수 추가가 되게 했는데 점수 추가는 잘 되는데
코드를 다시 보니 document를 사용 했고
이미지가 사라지긴 하는데 있던 자리에 이미지가 사라지니 옆에 이미지가
움직이는 현상 그래서 none을 하지말고 block한 상태로 투명도를 낮추는 걸로 생각함
이미지를 클릭하면 투명도가 안먹혀서
div로 한번더 감싼 후 이 div를 클릭 하면 div의 투명도를 0로 주는 형태로 수정함
const imgDivRefs = useRef<Array<HTMLDivElement | null>>([]);
const handleImgClick = (index: number) => {
const clickedImgRef = imgDivRefs.current[index];
if (clickedImgRef) {
clickedImgRef.classList.add("transparent_image");
SetScore((prevScore) => prevScore + 1);
}
};
{imgUrl.map((item, index) => (
<div key={index} className="imgBox_div" onClick={() => handleImgClick(index)} ref={(ref) => (imgDivRefs.current[index] = ref)}>
<img
key={index}
id={`imgMove${index}`}
src={item}
alt="고양이 이미지"
style={{ opacity: "0" }}
/>
</div>
))}
useRef로 div에 접근
<Array<HTMLDivElement | null>> ===<HTMLDivElement | null>[]
clickedImgRef 유무 따라서 클래스 추가 후 점수 추가
(ref) => (imgDivRefs.current[index] = ref)
ref는 React에서 자동으로 생성된 참조 객체
(ref) => (imgDivRefs.current[index] = ref)에서 ref 인자를 활용하여 해당 div 요소에 대한 참조를 배열에 할당합니다.
ref 인자는 React에서 자동으로 생성된 참조 객체 DOM 요소에 대한 정보를 가지고 있고
참조 객체를 받아와서 배열인 imgDivRefs.current에 할당