【问题标题】:How to use React.useRef() in class component?如何在类组件中使用 React.useRef()?
【发布时间】:2020-06-21 13:16:20
【问题描述】:

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

我该怎么做?

【问题讨论】:

    标签: reactjs react-toastify


    【解决方案1】:

    useRef() 是反应钩子之一,钩子用于功能组件,但如果您想在基于类的组件中创建引用,

    您可以从类构造函数中执行此操作,如下面的代码:

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

    检查React.createRef()

    【讨论】:

      【解决方案2】:

      在构造函数中赋值,即绑定this

      createRef !== useRef, useRef 用于在重新渲染时保留值,对于类组件中的值,您需要将其与this 绑定而不是createRef

      【讨论】:

        猜你喜欢
        • 2020-06-14
        • 1970-01-01
        • 2020-04-27
        • 1970-01-01
        • 2021-06-27
        • 1970-01-01
        • 2020-01-16
        • 2019-07-29
        • 2019-12-18
        相关资源
        最近更新 更多