react ref with focus() doesn't work without setTimeout (my example)

后端 未结 2 914
青春惊慌失措
青春惊慌失措 2020-12-18 21:12

I have encounter this problem, the .focus() only works with setTimeout if i take it out and it stop working. can anyone explain me what\'s the reas

2条回答
  •  醉酒成梦
    2020-12-18 21:35

    Using setTimeout() is a bad idea and using componentDidMount() is irrelevant. You may find the answer to your question in the following example:

    In a parent component I render a primereact Dialog with an InputText in it:

    
       {this.nameInp = nameInp}} .../>
      ...
    
    

    Initially, this.state.visible is false and the Dialog is hidden. To show the Dialog, I re-render the parent component by calling showDlg(), where nameInp is the ref to InputText:

    showDlg() {
      this.setState({visible:true}, ()=>{
        this.nameInp.element.focus();
      });
    }
    

    The input element gets the focus only after rendering has been accomplished and the setState callback function called.

    Instead of using the setState callback, in some cases you may simply use:

    componentDidUpdate(){
      this.nameInp.element.focus();
    }
    

    However, componentDidUpdate() is being called every time you (re)render the component, including in case the InputText is hidden.

    See also: https://reactjs.org/docs/react-component.html#setstate

提交回复
热议问题