如何在类组件中使用React.useRef()?

时间:2020-06-21 13:16:20

标签: reactjs react-toastify

我需要在类组件中实现此代码。 这是为了在我的班级组件中使用带有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>
  )
}

我该怎么做?

1 个答案:

答案 0 :(得分:7)

useRef()属于react钩子,钩子应在Functional组件中使用,但是如果要在基于类的组件中创建引用,

您可以从类构造函数中执行以下操作:

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

选中React.createRef()