이미지 슬라이드를 구현 설계
핵심내용
1. styled-components 사용 -> css에서 쉽게 js 변수에 접근하기 위해
2. 음수 마진 이해
3. 이미지들을 다 가로로 정렬해 놓고 경계선 넘는 것을 hidden 처리
4. useRef를 이용해 current.style을 가져와야 한다
5. 마지막 슬라이드에서 오른쪽 넘기기 버튼을 누르면 처음으로 돌아온다
6. styled-components 사용할때 변수 이름을 반드시 대문자로 해야한다
이미지 3개를 이용해 슬라이드를 구현한다고 가정
한개의 이미지컨테이너에
이미지 3개를 flex 가로 방향으로 정렬해야한다
const LifeImage = (props) => {
const [currentSlide, setCurrentSlide] = useState(0);
const slideRef = useRef(null);
console.log('렌더링 진행');
const TOTAL_SLIDES = 2;
const moveRight = () => {
if (currentSlide >= TOTAL_SLIDES) {
setCurrentSlide(0);
} else {
setCurrentSlide(currentSlide + 1);
}
};
const moveLeft = () => {
if (currentSlide === 0) {
setCurrentSlide(TOTAL_SLIDES);
} else {
setCurrentSlide(currentSlide - 1);
}
};
useEffect(() => {
console.log('currentSlide 변동때문에 useEffect 실행!!');
console.log('currentSlide 확인', currentSlide);
slideRef.current.style.transition = "all 0.5s ease-in-out";
slideRef.current.style.transform = `translateX(-${currentSlide}00%)`;
}, [currentSlide]);
return (
<Container>
<SliderContainer ref={slideRef}>
<SliderImg src="img/tattoo.png"/>
<SliderImg src="img/tattoo2.png"/>
<SliderImg src="img/tattoo4.png"/>
</SliderContainer>
<ArrowBackBtn onClick={moveLeft}>
<ArrowBackIosIcon sx={{fontSize: 40}}/>
</ArrowBackBtn>
<ArrowForwardBtn onClick={moveRight}>
<ArrowForwardIosIcon sx={{fontSize: 40}}/>
</ArrowForwardBtn>
</Container>
);
};
css 부분
const Container = styled.div`
width: 60%;
display: flex;
position: relative;
justify-content: center;
align-items: center;
background-color: antiquewhite;
overflow: hidden;
`
const SliderContainer = styled.div`
width: 100%;
height: 100%;
display: flex;
`
const SliderImg = styled.img`
padding: 0px;
width: 30rem;
height: 30rem;
object-fit: cover;
`
const ArrowBackBtn = styled.button`
position: absolute;
color: white;
width: 5rem;
top: 45%;
left: 0%;
background-color: transparent;
&:hover {
color: red;
}
`
const ArrowForwardBtn = styled.button`
position: absolute;
color: white;
width: 5rem;
top: 45%;
right: 0%;
background-color: transparent;
&:hover {
color: red;
}
`