본문 바로가기

프론트엔드관련 책예제실습정리/리기술요약

ref:DOM에 이름달기

JSX안에서 id를 사용할 경우 같은 컴포넌트가 여러번 사용되었을때 문제가 생김
=>(대안)ref는 전역적 작동하지 않고 컴포넌트 내부에서만 작동
**ref 사용하는 이유 : 가끔 state로만 해결할 수 없는 기능들이 있다.
(특정 input 포커스, 스크롤박스조작, canvas요소 그림그리기)

**ref로 전달받은 컴포넌트 메서드는 
부모 자식 구조일때만 사용 가능 
(함수형 컴포넌트에서는 useRef라는 Hook함수를 사용: React.createRef와 유사)

////App.js
import React from "react";
import Validation from "./ValidationSample";

const App = () => {
  return <Validation />;
};

export default App;


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

class ValidationSample extends Component {
  state = {
    password: "",
    clicked: false,
    validated: false,
  };

  handleChange = (e) => {
    this.setState({
      password: e.target.value,
    });
  };
  handleButtonClick = () => {
    this.setState({
      clicked: "true",
      validated: this.state.password === "000",
    });
  };

  render() {
    return (
      <div>
        <input
          type="password"
          value={this.state.password}
          onChange={this.handleChange}
          className={
            this.state.clicked
              ? this.state.validated
                ? "success"
                : "failure"
              : ""
          }
        />
        <button onClick={this.handleButtonClick}>클릭</button>
      </div>
    );
  }
}

export default ValidationSample;

input에 ref 달고 버튼 onClick 이벤트 수정

  (...)
  handleButtonClick = () => {
    this.setState({
      clicked: "true",
      validated: this.state.password === "000",
    });
    this.input.focus();
  };

  render() {
    return (
      <div>
        <input
          ref={(ref) => {
            this.input = ref;
          }}
 (...)

**컴포넌트에 ref 달고 내부 메서드 사용

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

class App extends Component {
  render() {
    return (
      <div>
        <ScrollBox ref={(ref) => (this.scrollBox = ref)} />
        <button onClick={() => this.scrollBox.scrollToBottom()}>아래로</button>
      </div>
    );
  }
}
export default App;


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

class ScrollBox extends Component {
  scrollToBottom = () => {
    const { scrollHeight, clientHeight } = this.box;
    this.box.scrollTop = scrollHeight - clientHeight;
  };

  render() {
    const style = {
      border: "1px solid #000",
      height: "300px",
      width: "300px",
      overflow: "auto",
      position: "relative",
    };
    const innerStyle = {
      width: "100%",
      height: "650px",
      background: "linear-gradient(white,black)",
    };
    return (
      <div
        style={style}
        ref={(ref) => {
          this.box = ref;
        }}
      >
        <div style={innerStyle} />
      </div>
    );
  }
}

export default ScrollBox;

'프론트엔드관련 책예제실습정리 > 리기술요약' 카테고리의 다른 글

08hooks/useMemo,useCallback,useRef  (0) 2021.06.22
컴포넌트 반복  (0) 2021.06.11
이벤트핸들링2  (0) 2021.06.04
이벤트핸들링1  (0) 2021.06.04
컴포넌트2 -state  (0) 2021.06.04