Focusing div elements with React

后端 未结 6 1740
不思量自难忘°
不思量自难忘° 2020-12-15 06:16

Is it possible to focus div (or any other elements) using the focus() method?

I\'ve set a tabIndex to a div element:

6条回答
  •  误落风尘
    2020-12-15 06:26

    This is the problem:

    this.setState({ active: state });
    this.refs.component.focus();
    

    Set state is rerendering your component and the call is asynchronous, so you are focusing, it's just immediately rerendering after it focuses and you lose focus. Try using the setState callback

    this.setState({ active: state }, () => {
       this.refs.component.focus();
    });
    

提交回复
热议问题