5. REF

hey hey·2021년 12월 10일
0

리액트 배우기

목록 보기
7/26
post-thumbnail

DOM에 이름을 다는 방법

  • DOM을 직접적으로 건드려야 할 때 사용

state로 input 창 색 바꿔보기

import React,{Component} from "react";
import '../App.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}>검증하기</button>  
      </div>
    )
  }

}

export default ValidationSample

버튼이 onClick 이 되면 clicked이 되었다라고 바뀌고, validated가 '0000'이면 true 아니면 false

input 창에서

  • onChange로 적을 때마다 password가 바뀌게 해주었다.
  • className 을 지정해줘서 style이 변하게 만들어 줬다 → this.state.clicked ? → 클릭이 되어있다면 this.state.validated? 유효성 검사가 true 인지 아닌지 확인 후 'success' or 'failure' 로 반환한다 → 클릭이 안되어있다면 빈값 반환

DOM을 꼭 써야하는 상황

  • 특정 input에 포커스 쓰기
  • 스크롤 박서 조작하기 ..

ref 사용

콜백 함수를 통한 ref 설정 (권장)

  • ref를 달고자 하는 요소에 ref라는 콜백 함수를 props로 전달해주면 된다.
  • 이 콜백 함수는 ref 값을 파라미터로 전달 받는다
  • 함수 내부에서 파라미터로 받은 ref를 컴포넌트의 멤버 변수로 설정해 준다.

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

this.변수명은 input요소의 DOM을 가리킨다.

createRef

  • 같은 내용
import React,{Component} from "react";

class RefSample extends Component{
  input = React.createRef()

  handleFocus= () =>{
    this.input.current.focus()
  }
  render(){
    return (
      <div>
        <input ref={this.input}/>
      </div>
    )
  }
}
export default RefSample

input = React.createRef()

input에 ref 달기

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

handleButtonClick = () =>{
    this.setState({
      clicked:true,
      validated:this.state.password ==='0000'
    })
    this.input.focus()
}
  • input 에 ref로 속성을 달고,
  • 버튼 클릭시 input에 focus가 되게끔 만들기

컴포넌트에 ref 달기

  • (부모← 자식)
  • 컴포넌트 내부에 있는 DOM을 컴포넌트 외부에서 사용할 때 사용

사용법

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

스크롤박스 만들기

import React, {Component} from 'react'

class ScrollBox 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 (
      <div
        style={style}
        ref ={(ref)=>{this.box=ref}}>
          <div style={innerStyle}></div>
      </div>
    )
  }
}
export default ScrollBox

<div ref ={(ref)=>{this.box=ref}}>

ref 설정하기

스크롤바 내리는 버튼 만들기

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

/App.js
<ScrollBox ref={(ref)=>this.ScrollBox=ref}/>
  
<button onClick={()=>this.ScrollBox.scrollToBottom()}>
    맨 밑으로
</button>

scrollToBottom

scrollTop : 세로 스크롤바 위치

scrollHeight : 스크롤이 있는 박스 안의 div 높이

이렇게 만든 메서드는 부모 컴포넌트에서 ScrollBox에 ref를 달면 사용 가능하다.

profile
FE - devp

0개의 댓글