farmeter / random

0 stars 0 forks source link

React의 Ref #53

Open farmeter opened 2 years ago

farmeter commented 2 years ago

ref란?

ref가 필요없는 경우

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
                    type="password"
                    value={this.state.password}
                    onChange={this.handleChange}
                    className={this.state.clicked ? (this.state.validated ? 'success' : 'failure') : ''}
                  />
              <button onClick={this.handleButtonClick}>검증하기</button>
          </div>
          );
      }}

ref를 사용 하는경우

  1. 기본적인 방법 : 콜백 함수를 사용하는 것

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

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

    • this.input은 input 요소의 DOM을 가리킴
    • ref 이름은 자유롭게
  2. 두번째 방법 - createRef를 사용

    • v16.3부터 지원
      
      class RefSample extends Componenet {
      input = React.createRef();

    handleFocus = () => { this.input.current.focus(); }

    render() { return (

    );

    } }

    
    - createRef를 사용하여 컴포넌트 내부에서 멤벼변수로 React.createRef()를 담아줌
    - 해당 멤버 변수를 ref를 달고자 하는 요소에 ref.proprs로 넣어줌
    - this.input.current를 조회하면 DOM에 접근 가능(콜백과는 달리.current를 넣어주어야 함)

컴포넌트에 ref 달기

<MyComponent
    ref={(ref) => {this.myComponent=fer}}
/>
MyComponent의 내부 메서드 및 멤버변수에 접근가능

class ScrollBox extends Component {
    render() {
        const style = {... } 
        const innerStyle ={...}

        scrollToBottom = () => {
            const { scrollheight, clientHeight } = this.box;
            this.box.scrollTop = scrollHeight - clientHeight;
        }

        return (
            <div
                style={style}
                ref={(ref) => {this.box=ref}}>
                <div style={innerStyle}/>
            </div>
        );
    }
}
..상위 App컴포넌트에서 사용할 때
<div>
    <ScrollBox ref={(ref) => this.scrollBox=ref} />
    <button onClick={() => this.scrollBox.scrollToBottom()}>
        맨 밑으로
        </button>
    ...

정리