티스토리 뷰

ref였나?

아래 Message에서 Welome 객체를 어떻게 참조하지?

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

class Message extends React.Component {
  render() {
    return <Welcome>;
  }
}

 

방법을 찾은 것 같다

Ref와 DOM

https://ko.reactjs.org/docs/refs-and-the-dom.html

 

Ref와 DOM – React

A JavaScript library for building user interfaces

ko.reactjs.org

⚠️ 이 아래 내용은 위 React.js 페이지 내용의 복붙입니다.

Ref 생성

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.myRef = React.createRef();  
  }
  
  render() {
    return <div ref={this.myRef} />;  
  }
  
}

Ref 접근

const node = this.myRef.current;
함수 컴포넌트는 인스턴스가 없기 때문에 함수 컴포넌트에 ref 어트리뷰트를 사용할 수 없습니다.

DOM 엘리먼트에 Ref 사용

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // textInput DOM 엘리먼트를 저장하기 위한 ref를 생성합니다.
    this.textInput = React.createRef();    
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // DOM API를 사용하여 명시적으로 text 타입의 input 엘리먼트를 포커스합니다.
    // 주의: 우리는 지금 DOM 노드를 얻기 위해 "current" 프로퍼티에 접근하고 있습니다.
    this.textInput.current.focus();  
  }

  render() {
    // React에게 우리가 text 타입의 input 엘리먼트를
    // 우리가 생성자에서 생성한 `textInput` ref와 연결하고 싶다고 이야기합니다.
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />        
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

⚠️ "클래스  컴포넌트"에 ref 사용하기

class AutoFocusTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();  
  }

  componentDidMount() {
    this.textInput.current.focusTextInput();  
  }

  render() {
    return (
      <CustomTextInput ref={this.textInput} />    
    );
  }
}

Ref와 함수 컴포넌트

함수 컴포넌트에선 'Forwarding Refs'라는 방식을 사용해야 함.

https://ko.reactjs.org/docs/forwarding-refs.html

 

Forwarding Refs – React

A JavaScript library for building user interfaces

ko.reactjs.org

함수형 컴포넌트에서 클래스형 컴포넌트에 ref 어트리뷰트를 사용하는 것은 가능

function CustomTextInput(props) {
  // textInput은 ref 어트리뷰트를 통해 전달되기 위해서
  // 이곳에서 정의되어야만 합니다.  const textInput = useRef(null);

  function handleClick() {    
    textInput.current.focus();
  }

  return (
    <div>
      <input
        type="text"        
        ref={textInput} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}

콜백 ref

ref 어트리뷰트에 함수를 전달해서 인스턴스나 DOM 엘리먼트를 인자로 전달받는 방식

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);

    this.textInput = null;
    this.setTextInputRef = element => {
      this.textInput = element;    
    };
    this.focusTextInput = () => {      
      // DOM API를 사용하여 text 타입의 input 엘리먼트를 포커스합니다.
      if (this.textInput) this.textInput.focus();
    };
  }

  componentDidMount() {
    // 마운트 되었을 때 자동으로 text 타입의 input 엘리먼트를 포커스합니다.
    this.focusTextInput();  
  }

  render() {
    // text 타입의 input 엘리먼트의 참조를 인스턴스의 프로퍼티
    // (예를 들어`this.textInput`)에 저장하기 위해 `ref` 콜백을 사용합니다.
    return (
      <div>
        <input
          type="text"
          ref={this.setTextInputRef}        
        />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}        
        />
      </div>
    );
  }
}

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
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
글 보관함