React: set focus on componentDidMount, how to do it with hooks?

前端 未结 2 993
长情又很酷
长情又很酷 2021-01-11 09:24

In React, with classes I can set the focus to an input when the component loads, something like this:

class Foo extends React.Component {
    txt1 = null;

          


        
2条回答
  •  不思量自难忘°
    2021-01-11 10:04

    You can use the useRef hook to create a ref, and then focus it in a useEffect hook with an empty array as second argument to make sure it is only run after the initial render.

    const { useRef, useEffect } = React;
    
    function Foo() {
      const txt1 = useRef(null);
    
      useEffect(() => {
        txt1.current.focus();
      }, []);
    
      return ;
    }
    
    ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题