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

ch02.ref 사용

webmaster 2021. 11. 9. 12:01
728x90

콜백 함수를 통한 ref 설정

  • ref를 달고자 하는 요소에 ref라는 콜백 함수를 props로 전달해준다.
  • 이 콜백 함수는 ref 값을 파라미터로 전달받아 함수 내부에서 ref를 컴포넌트의 멤버 변수로 설정한다.
    • <input ref={(ref) => {this.input=ref}} />
    • this.input은  input요소의 DOM을 가리키게 된다.

createRef를 통한 ref 설정

  • 리액트에 내장되어 있는 createRef라는 함수를 사용한다.
  • 리액트 v16.3부터 도입되었다.
  • import React, { Component } from "react";
    
    class RefSample extends Component {
      input = React.createRef();
      handleFocus = () => {
       	this.input.focus();
      };
     
    
      render() {
        return (
          <div>
            <input ref={this.input} />
          </div>
        );
      }
    }
    
    export default RefSample;
  • 멤버 변수로 React.createRef()를 담아준 뒤, 해당 멤버 변수를 ref를 달고자 하는 요소의 ref props로 넣어주면 된다.
  • DOM에 접근하기 위해 this.input.current로 접근하면 된다.

이전 코드 변환하기

  • 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 === "0000",
        });
        this.input.focus();
      };
    
      render() {
        return (
          <div>
            <input
              ref={(ref) => (this.input = ref)}
              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;
    onclick이벤트 발생 시 input에 포커스를 주도록 변경하였다.

 

728x90