ReactJS: How-to set focus to input-element when it enters the DOM?

后端 未结 2 1528
时光取名叫无心
时光取名叫无心 2021-02-14 19:53

How to set focus to an input element when it enters the DOM?

Scenario

When a button is clicked the input element is displayed. How to set the focu

相关标签:
2条回答
  • 2021-02-14 20:14

    In the componentDidMount and componentDidUpdate hooks do this:

    ReactDOM.findDOMNode(this.refs.myInput).focus()
    
    0 讨论(0)
  • 2021-02-14 20:31

    Assuming you only need one visible input on the page at a time to have autofocus Poh Zi How's suggestion of using the autofocus is probably the simplest.

    <input type="text" autofocus/>

    should do the trick, no JS needed!

    0 讨论(0)
提交回复
热议问题