멘토님에게 리뷰를 받고 리팩토링 과정을 거치며 코드를 한층 더 간결하게 작성할 수 있었습니다.

 

before

handleNextSlider = () => {
    const sliderElement = this.sliderRef.current;
    const itemElement = this.itemRef.current;
    const itemWidth = Math.ceil(itemElement.getBoundingClientRect().width);
    if (
      this.state.transFormPosition ===
      (sliderElement.getElementsByClassName('anotherItem').length - 4) *
        -itemWidth
    ) {
      return;
    }
 
    this.setState(
      {
        transFormPosition: this.state.transFormPosition - itemWidth,
      },
      () => {
        sliderElement.style.transform = `translate(${this.state.transFormPosition}px)`;
      }
    );
  };

 

 

after

  handleNextSlider = () => {
    const sliderElement = this.sliderRef.current;
    const { currentIndex } = this.state;
    const { subImage } = this.props;
 
    if (this.itemRef.current) {
      const itemWidth = Math.ceil(
        this.itemRef.current.getBoundingClientRect().width
      );
      if (currentIndex === subImage - 4) {
        return;
      }
 
      this.setState(
        {
          currentIndex: currentIndex + 1,
        },
        () => {
          sliderElement.style.transform = `translate(-${
            this.state.currentIndex * itemWidth
          }px)`;
        }
      );
    }
  };

 

ref를 통하여 slider의 위치를 이미지의 너비만큼 이동하도록 만든 함수입니다.

이미지의 너비는 getBoundingClientRect() 메소드를 사용하여 측정하였습니다.

화면상에서 보이는 이미지는 4개이므로 현재 index의 위치와 이미지 배열의 길이 -4가 같으면 더 이상

slider의 위치를 옮기지 않도록 하였습니다.

'Wecode > Project' 카테고리의 다른 글

[Project-1] watCU - 별점,별점그래프  (0) 2021.09.12
[Wecode] 1차 Project : watCU 후기  (0) 2021.07.18

+ Recent posts