programing

클래스 컴포넌트에서 React.useRef()를 사용하는 방법

elseif 2023. 3. 20. 21:36

클래스 컴포넌트에서 React.useRef()를 사용하는 방법

이 코드를 클래스 컴포넌트에 구현해야 합니다.react-toastify와 함께 클래스 컴포넌트의 업로드 진행률을 사용하기 위해서입니다.

function Example(){
  const toastId = React.useRef(null);
  function handleUpload(){
    axios.request({
      method: "post", 
      url: "/foobar", 
      data: myData, 
      onUploadProgress: p => {
        const progress = p.loaded / p.total;
        if(toastId.current === null){
            toastId = toast('Upload in Progress', {
            progress: progress
          });
        } else {
          toast.update(toastId.current, {
            progress: progress
          })
        }
      }
    }).then(data => {
      
      toast.done(toastId.current);
    })
  }
  return (
    <div>
      <button onClick={handleUpload}>Upload something</button>
    </div>
  )
}

내가 어떻게 그럴 수 있을까?

useRef()기능 컴포넌트에 사용되는 리액트 훅 중 하나입니다.그러나 클래스 기반 컴포넌트에 참조를 작성하려면 아래 코드와 같이 클래스 생성자에서 참조를 작성할 수 있습니다.

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

React.createRef()선택합니다.

컨스트럭터에서 값 할당(바인드)this.

createRef !== useRef,useRef이 값은 재접속된 값을 유지하기 위해 사용되며 클래스 내의 컴포넌트에서는 이 값을 바인드해야 합니다.this것은 아니다.createRef

언급URL : https://stackoverflow.com/questions/62499061/how-to-use-react-useref-in-class-component