티스토리 뷰

Programming

[React] DOM에 이름 달기

whilescape 2019. 12. 7. 09:35

Introduction

  1. 일반 HTML에서 DOM 요소에 이름을 달 때, id를 사용

    <div id="my-element"></div>
  2. 특정 DOM 요소에 어떤 작업을 해야 할 때 이렇게 요소에 id를 달면 css에서 특정 id에 특정 스타일을 적용하거나
    js에서 해당 id를 가진 요소를 찾아서 작업할 수 있다.

  3. HTML과 비슷하게, react project 내부에서 dom에 이름을 다는 방법 : 이를 ref 개념이라고 한다.

5.1 when to use the "ref"

  1. 우선 HTML에서 getElementById()가 어떻게 사용되는지 봅시다
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <style>
      .success{
        background-color: green;
      }
      .failure{
        background-color: red;
      }
    </style>
    <script>
      function validate(){
        var input = document.getElementById('password');
        input.className='';
        if(input.value === '0000'){
          input.className = 'success';
        }else{
          input.className = 'failure';
        }
      }
    </script>
  1. react에서는 굳이 dom에 접근하지 않아도 state로 구현할 수 있다.
  • 구현 순서
  • 컴포넌트 만들기 > input에 ref 달기 > button onClick 마다 input에 focus 주기
.success{
    background-color: lightgreen;
}

.failure{
    background-color: lightcoral;
}
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'
        })
    }

    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}
                >Click for Validation</button>
            </div>
        )
    }
}

export default ValidationSample;
  • 위 코드와 같이 state를 사용하여 원하는 기능을 구현하였지만, 가끔 state만으로 해결할 수 없는 기능이 있다

    • 특정 input에 포커스 주기

    • 스크롤 박스 조작하기

    • Canvas 요소에 그림 그리기 등

      이럴 때 ref를 사용한다

  1. ref 값으로는 콜백 함수를 전달, 콜백함수 내부에서 컴포넌트의 멤버 변수에 ref를 담는 코드를 작성한다.

    <input ref={(e) => {this.input=e}}></input>

5.3 컴포넌트에 ref 달기

  1. 컴포넌트에 ref를 다는 방법은 dom에 ref를 다는 방법과 똑같다.

노트-ES6의 비구조화 할당 문법

  1. 객체에서 특정값을 추출하여 따로 레퍼런스를 만들 때 유용
const object = {
  foo:1,
  boo:2
};
const {f, b} = object;  
console.log(f,b); // 1 2
  1. 비구조화 할당 문법은 리액트 컴포넌트에서 state나 props를 참조할 때 자주 사용된다.

    render(){
    const{name, number} = this.props;
    return(
     <div>
         <div>{name}</div>
         <div>{number}</div>
     </div>
     }
    }
  2. python에서도 이런 느낌의 문법이 존재하지

    dp = [[1,2], [2,3]]
    x, y = d[0] 
    print(x, y) # 1 2가 출력됩니다

ref에 대한 내 느낌 정리

  1. 문법을 내 방식으로 이해해봅시다.
    ref = {(e) => {this.mybox=e}}
  • 위 문법은 특정 DOM 요소, 예를 들면, div(태그)의 속성값으로 ref를 위와 같이 설정하면
    해당 div를 this.mybox라는, 일종의 변수에 할당하는 느낌이다.

  • 여기서 this.mybox=e에서 this.myboxxxx=e와 같이 그 이름은 정하기 나름이다.
    다른 곳에서 이것을 사용하고 싶으면 여기서 정의한 이름을 그대로 사용하면 됩니다.

  • 확실하게 정리!
    this.mybox라는 일종의 멤버 변수를 만들고 그것을 e로 초기화하는 느낌이다!

'Programming' 카테고리의 다른 글

[React] 컴포넌트의 라이프 사이클  (0) 2019.12.07
[React] 컴포넌트 반복  (0) 2019.12.07
[React] 이벤트 핸들링  (0) 2019.12.06
[React] 컴포넌트  (0) 2019.12.06
[React] 리액트 기초 공부-JSX 문법  (0) 2019.12.06
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함