Trying to use React.createRef() but getting error: TypeError: Cannot read property 'focus' of null

Trying to use React.createRef() but getting error: TypeError: Cannot read property 'focus' of null

文件中的代码是:

import React, { Component } from 'react'

class LoginModal extends Component {

    constructor(props) {
        super(props)
        this.mobileInput = React.createRef();    // <------------CREATED REF Here
    }

   componentDidMount() {
        this.mobileInput.current.focus()        // <<<------------Getting ERROR here
   }

render() {
        return (
          <input
            type='number'
            onChange={this.handleInputChange('mobile')}
            className='form-control'
            placeholder='Enter mobile'
            name='mobile'
            ref={this.mobileInput}           // <<<------------added ref to input
         />
       )
    }

我得到的错误是:

TypeError: 无法读取 属性 'focus' 的 null

我尝试过的:

*文件中有更多代码。为了清楚起见,我删除了不必要的代码。

我找到了答案。只需要用这个。

<input ref={input => input && input.focus()}/>