AutoFocus an input element in react JS

后端 未结 2 1031
南笙
南笙 2020-12-29 04:59

I am unable to autofocus the input tag rendered in this component. What am I missing here?

class TaskBox extends Component {
  constructor() {
    super();
          


        
相关标签:
2条回答
  • 2020-12-29 05:39

    There is a attribute available for auto focusing autoFocus, we can use that for auto focusing of input element instead of using ref.

    Using autoFocus with input element:

    <input autoFocus />

    We can also use ref, but with ref we need to call focus method at correct place, you are calling that in componentWillUpdate lifecycle method, that method will not triggered during initial rendering, Instead of that use componentDidMount lifecycle method:

    componentDidMount(){
        this.focus();
    }
    

    shouldComponentUpdate: is always called before the render method and enables to define if a re-rendering is needed or can be skipped. Obviously this method is never called on initial rendering. It will get called only when some state change happen in the component.

    componentWillUpdate gets called as soon as the the shouldComponentUpdate returned true.

    componentDidMount: As soon as the render method has been executed the componentDidMount function is called. The DOM can be accessed in this method, enabling to define DOM manipulations or data fetching operations. Any DOM interactions should always happen in this.

    Reference: https://facebook.github.io/react/docs/react-component.html

    0 讨论(0)
  • 2020-12-29 05:44

    Set an ID to the input and then use .setAttribute('autoFocus', true) to the element when you want it focused

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