将 myR 转换为 hooks 版本

Conver myRef to hooks version

我找到了这个答案:

但我不知道如何转换:

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

componentDidMount(){
  this.myRef.current.focus();
}

<input type="text"  ref={this.myRef} />

反应挂钩版本。

我试过这样做:

const myRef = () => {
  React.createRef().current.focus();
}

<input type="text"  ref={myRef} />

但出现错误:

TypeError: Cannot read property 'focus' of null

以及useRef you'll need to use useEffect too which runs after a render. The [] means that it only runs once

import React, { useRef, useEffect } from 'react';

function Component() {

  const ref = useRef(null);

  useEffect(() => {
    ref.current.focus();
  }, []);

  return <input type="text"  ref={ref} />;

}