5.3.3 컴포넌트에 메서드 생성

    컴포넌트에 스크롤바를 맨 아래쪽으로 내리는 메서드를 만들겠습니다. 자바스크립트로 스크롤바를 내릴 때는 DOM 노드가 가진 다음 값들을 사용합니다.

    scrollTop: 세로 스크롤바 위치(0~350)

    scrollHeight: 스크롤이 있는 박스 안의 div 높이(650)

    clientHeight: 스크롤이 있는 박스의 높이(300)

    스크롤바를 맨 아래쪽으로 내리려면 scrollHeight에서 clientHeight 높이를 빼면 되겠지요?

    ScrollBox.js

    import React, { Component } from 'react';
     
    class ScrollBox extends Component {
     
      scrollToBottom = () => {
        const { scrollHeight, clientHeight } = this.box;
        /*  코드에는 비구조화 할당 문법을 사용했습니다.
           다음 코드와 같은 의미입니다.
           const scrollHeight = this.box.scrollHeight;
           const clientHeight = this.box.cliengHeight;
        */
        this.box.scrollTop = scrollHeight - clientHeight;
      }
     
      render() {
        (...)
    }
     
    export default ScrollBox;

     

    scrollToBottom 메서드의 첫 번째 줄에서는 ES6의 비구조화 할당 문법을 사용했습니다.

    이렇게 만든 메서드는 부모 컴포넌트인 App 컴포넌트에서 ScrollBoxref를 달면 사용할 수 있습니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.