React:设置焦点在componentDidMount上,如何用钩子做?

Rod*_*igo 10 javascript reactjs

在React中,对于类,我可以在组件加载时将焦点设置为输入,如下所示:

class Foo extends React.Component {
    txt1 = null;

    componentDidMount() {
        this.txt1.focus();
    }

    render() {
        return (
            <input type="text"
                ref={e => this.txt1 = e}/>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用新的钩子提议重写此组件.

我想我应该使用useEffect而不是componentDidMount,但我怎样才能重写焦点逻辑?

Tho*_*lle 16

您可以使用该useRef钩子创建一个ref,然后将其聚焦在useEffect具有空数组作为第二个参数的钩子中,以确保它仅在初始渲染之后运行。

const { useRef, useEffect } = React;

function Foo() {
  const txt1 = useRef(null);

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

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

ReactDOM.render(<Foo />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)

  • @notgiorgi 给 `useRef` 的参数是 ref 的 `current` 属性应该是什么值,所以初始值为 `{ current: null }`。将一个空数组作为 `useEffect` 的第二个参数,使得效果只在初始渲染后运行一次,这正是 OP 想要的。 (2认同)
  • 啊,谢谢,我忘了`useEffect`运行_after_初始渲染不是_before_ (2认同)