如何在类组件中使用 React.useRef()? [英] How to use React.useRef() in class component?

查看:98
本文介绍了如何在类组件中使用 React.useRef()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在类组件中实现这段代码.这是为了在我的类组件中使用 react-toastify 上传进度

函数示例(){const toastId = React.useRef(null);函数句柄上传(){axios.request({方法:发布",网址:/foobar",数据:我的数据,onUploadProgress: p =>{const 进度 = p.loaded/p.total;if(toastId.current === null){toastId = toast('上传中', {进步:进步});} 别的 {toast.update(toastId.current, {进步:进步})}}}).那么(数据=> {toast.done(toastId.current);})}返回 (<div><button onClick={handleUpload}>上传内容</button>

)}

我该怎么做?

解决方案

useRef() 是 react 钩子之一,钩子旨在用于功能组件,但如果您想在基于类的组件,

你可以像下面的代码一样从类构造函数中做到这一点:

 构造函数(道具){超级(道具);this.myRef = React.createRef();}

检查 React.createRef().

I need this code to be implemented in class component. It is in order to use a upload progress in my class component with 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>
  )
}

How can i do that?

解决方案

useRef() is among react hooks and hooks are meant to be used in Functional components but if you want to create a reference in a class-based component,

you can do it from the class constructor like the codes bellow:

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

Check React.createRef().

这篇关于如何在类组件中使用 React.useRef()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆