리액트/ref:DOM에 이름달기

ch03.컴포넌트에 ref 달기

webmaster 2021. 11. 9. 12:34
728x90
  • 컴포넌트 내부에 있는 DOM을 컴포넌트 외부에서 사용할 때 쓴다.
    <MyComponent ref={(ref)=>{this.myComponent=ref}} />​
    MyComponent 내부의 메서드, 멤버 변수에도 접근이 가능하다.
  • import React, { Component } from "react";
    
    class ScrollBox extends Component {
      //스크롤바를 가장 밑으로 내리는 메소드
      scrollToBottom = () => {
        const { scrollHeight, clientHeight } = this.box;
        //const scrollHeight = this.box.scrollHeight;
        //const clientHeight = this.box.clientHeight;
        //와 같은 의미
        this.box.scrollTop = scrollHeight - clientHeight;
      };
    
      render() {
        const style = {
          border: "1px solid black",
          height: "300px",
          width: "300px",
          overflow: "auto",
          position: "relative",
        };
    
        const innerStyle = {
          background: "linear-gradient(white,black)",
          width: "100%",
          height: "650px",
        };
        return (
          <div
            style={style}
            ref={(ref) => {
              this.box = ref;
            }}
          >
            <div style={innerStyle} />
          </div>
        );
      }
    }
    export default ScrollBox;
  • import React, { Component } from "react";
    import ScrollBox from "./ScrollBox";
    
    
    class App extends Component {
      render() {
        //주의 할 점 : onclick= {this.scrollBox.scrollToBottom} 같은 형식으로 작성하여도 되지만,
        //            처음 렌더링 될때 this.scrollBox값이 undefined이기 때문에 값을 읽어오는 과정에서 오류발생
        //            따라서 화살표 문법을 사용하여 아예 새로운 함수를 만들고 그 내부에서 this.scrollBox.scrollToBottom 메소드를
        //            실행하게 된다면 버튼을 누를떄 값을 읽어 와서 실행하기 떄문에 오류가 발생하지 않는다.
        return (
          <div>
            <ScrollBox ref={(ref) => (this.scrollBox = ref)} />
            <button onClick={() => this.scrollBox.scrollToBottom()}>
              맨 밑으로
            </button>
          </div>
        );
      }
    }
    
    export default App;
  • 함수형 컴포넌트에서의 ref는 useRef라는 Hook함수를 사용한다.

 

 

728x90

'리액트 > ref:DOM에 이름달기' 카테고리의 다른 글

ch02.ref 사용  (0) 2021.11.09
ch01. ref는 어떤 상황에서 사용해야 할까?  (0) 2021.11.09