클래스 컴포넌트에서 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
'programing' 카테고리의 다른 글
ReactJS: onClick 핸들러를 자 컴포넌트에 배치해도 부팅되지 않음 (0) | 2023.03.20 |
---|---|
Wordpress - 작성자 이미지 가져오기 (0) | 2023.03.20 |
스프링 캐시 Java에서 여러 캐시 매니저 구성을 사용하는 방법 (0) | 2023.03.20 |
NSJON Serialization 오류 - JSON 쓰기(메뉴)에 잘못된 유형이 있습니다. (0) | 2023.03.20 |
ui-bootstrap-tpls.min.js와 ui-bootstrap.min.js의 차이점은 무엇입니까? (0) | 2023.03.20 |