Focusing div elements with React

后端 未结 6 1741
不思量自难忘°
不思量自难忘° 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:42

    React redraws the component every time you set the state, meaning that the component loses focus. In this kind of instances it is convenient to use the componentDidUpdate or componentDidMount methods if you want to focus the element based on a prop, or state element.

    Keep in mind that as per React Lifecycle documentation, componentDidMount will only happen after rendering the component for the first time on the screen, and in this call componentDidUpdate will not occur, then for each new setState, forceUpdate call or the component receiving new props the componentDidUpdate call will occur.

    componentDidMount() {
      this.focusDiv();
    },
    componentDidUpdate() {
      if(this.state.active)
        this.focusDiv();
    },
    focusDiv() {
      ReactDOM.findDOMNode(this.refs.theDiv).focus();
    }
    

    Here is a JS fiddle you can play around with.

提交回复
热议问题