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

MUH*_*BAL 8 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>
  )
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Mwi*_*ert 31

useRef() 在 React 钩子中,钩子是用来在功能组件中使用的,但是如果你想在基于类的组件中创建一个引用,

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

  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
Run Code Online (Sandbox Code Playgroud)

检查React.createRef()


Gar*_*yal 7

在构造函数中分配您的值,即与 绑定this

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

  • 你应该添加一个代码示例 (10认同)