4-3. 컴포넌트에 ref 설정하기

송한솔·2023년 4월 27일
0

ReactStudy

목록 보기
23/54

컴포넌트에 ref 설정하기

import React from 'react';
import ValidationSample from "./ValidationSample";
import ValidationSample1 from './ValidationSample1';
import ValidationSample2 from './ValidationSample2';

function App() {
  return (
    <div>
      <ValidationSample
        ref={(ref) => {this.ValidationSample=ref}}
      />
      <ValidationSample1/>
      <ValidationSample2/>

    </div>
  );
}

export default App;

이렇게 하면 ValidationSample 내부의 메서드 및 멤버 변수에도 접근할 수 있습니다.

즉, 부모 컴포넌트에서 자식 컴포넌트 내부의 ref에도 접근할 수 있다는 의미입니다.

예) ValidationSample.handleChange, ValidationSample.input

부모 컴포넌트에서 자식 컴포넌트 조작하기

01. 먼저 ScorollBox.js 컴포넌트 파일을 생성합니다.

// ScorollBox.js
import React, { Component } from "react";

class ScorollBox extends Component {
  render() {
    const style = {
      border: "1px solid black",
      height: "300px",
      width: "300px",
      overflow: "auto",
      position: "relative",
    };

    const innerStyle = {
      width: "100%",
      height: "650px",
      background: "linear-gradient(white,black)",
    };

    return (
      <>
        <h2>스크롤박스 생성</h2>
        <div
          style={style}
          ref={(ref) => {
            this.box = ref;
          }}
        >
          <div style={innerStyle}></div>
        </div>
      </>
    );
  }
}

export default ScorollBox;

이제 화면을 출력해봅시다.

스크롤 박스가 생성된 것을 볼 수 있습니다.

02. 외부에서 조작할 scrollToBottom함수를 추가해줍니다.

// ScorollBox.js
...
scrollToBottom = () => {
    const { scrollHeight, clientHeight } = this.box;
    // 이 코드는 구조분해 문법을 사용했습니다.
    // const scrollHiehgt = this.box.scrollHeight;
    // const clientHeight = this.box.clientHeight;
    // 이 코드는 앞의 코드와 같은 의미입니다.
    this.box.scrollTop = scrollHeight - clientHeight;
		this.box.style.border = "4px solid red";
    //작동 확인을 위한 가시성 css 변경
  };
...

03. App.js로 가서 조작할 컴포넌트명과 버튼을 추가합니다.

import React, { Component } from 'react';
import ValidationSample from "./ValidationSample";
import ValidationSample1 from './ValidationSample1';
import ValidationSample2 from './ValidationSample2';
import ScorollBox from './ScorollBox';
class App extends Component {
  render() {
    return (
      <div>
      <ValidationSample
        ref={(ref) => {this.ValidationSample=ref}}
      />
      <ValidationSample1/>
      <ValidationSample2/>
      <ScorollBox
        ref={(ref) => {this.scorollBox=ref}}
      />
      <button onClick={() => this.scorollBox.scrollToBottom()}>맨밑으로</button>
    </div>
    );
  }
}

export default App;

이렇게 자식 컴포넌트 요소에 있는 함수를 작동시키는 것을 볼 수 있습니다.

0개의 댓글