티스토리 뷰

FRONT-END/REACT

[REACT] REF

진심스테이크 2019. 1. 3. 21:12

 

ref (reference) : DOM에 이름을 다는 방법

- DOM을 직접 건드려야 할 때 사용

 

사용 방법

1. props를 설정하듯이 DOM에 ref 속성 추가

2. ref 값으로는 콜백 함수 전달

- 콜백 함수 : ref를 파라미터로 가짐

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

 

 

DOM을 꼭 사용해야 하는 상황

- 어쩔 수 없이 DOM에 직접적으로 접근해야함 -> ref 사용

1. 특정 input에 포커스(커서) 주기

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(); //버튼을 눌러도 포커스(커서)를 input에
    }

    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') : ''}
                >
                </input>
                <button onClick={this.handleButtonClick}>검증하기</button>
            </div>
        )
    }
}

export default ValidationSample;

 

2. 스크롤 박스 조작하기

- 컴포넌트에 ref 달기

<MyComponent ref={(ref) => {this.myComponent=ref}}/>

 

- 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 black',
            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>
            </div>
        )
    }
}

export default ScrollBox;

 

- 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;

 

 

 

3. Canvas 요소에 그림 그리기

 

 

 

 

 

 

 

 

 

 

 

 

'FRONT-END > REACT' 카테고리의 다른 글

[REACT] 함수형 컴포넌트  (0) 2019.04.29
[REACT] LIFE CYCLE - 수명주기  (0) 2019.04.27
[REACT] STATE  (0) 2019.01.03
[REACT] PROPS  (0) 2019.01.03
[REACT] JSX  (0) 2019.01.02
댓글