[React] ref 알아보기

4598 단어 ReactReact

⏳ ref

ref는 Dom 요소에 ID를 지정해준다고 생각하면 좋을 것 같습니다.
html 에서는 여러 태그들에게 구분 key 를 부여해줄 때 id 를 사용했었습니다

이를 통해 특정 id 를 가진 dom 요소를 핸들링하며 작업을 할 수 있었습니다.
이처럼 react 에서도 dom 요소에 특정 key를 부여해주는 것이 바로 ref입니다.

🎈 사용 방법

ref 생성

   constructor(props){
        super(props) 
        this.input = React.createRef();
   }
    

ref 적용

<input ref={this.input} ></input>
React.createRef(); 을 통해 ref를 생성하고 해당 태그에 ref={} 으로 적용할 수 있다.

🎐 활용

ref는 보통 state 만으로 해결할 수 없어, dom을 직접적으로 건드릴때 사용하게 됩니다.
ex) 특정 input 태그에 focus 지정, 스크롤박스 조작 등등..

활용 예시

    constructor(props){
        super(props) 

        this.onClickButton = this.onClickButton.bind(this);
        this.input = React.createRef();
    }
    onClickButton(){
        this.input.current.focus()     1️⃣
    }
    render() {
        return (
            <div>
                <input ref={this.input} ></input>
                <button onClick={this.onClickButton}>button</button>
            </div>
        )
    }

일반적으로는 button이 클릭되면 input 태그에서 focus가 사라지지만 ref를 이용하면
소스 1을 통해서 해당 태그에 focus를 줄 수 있습니다.

🔺 콜백 함수를 이용해서 ref 설정하기

<input ref={(refCb)=>{this.input = refCb}}></input>
refCb 값을 파라미터로 전달받으며 컴포넌트의 멤버변수로 설정해줍니다.


예시

onClickButton(){
        this.input.focus() 1️⃣
    }
    render() {
        return (
            <div>
                <input ref={(refCb)=>{this.input = refCb}}></input>
                <button onClick={this.onClickButton}>button</button>
            </div>
        )
    }

콜백 으로 지정하는 경우 React.createRef()를 통해 생성된 ref를 전달하는 대신,
함수를 전달합니다.

좋은 웹페이지 즐겨찾기