简体   繁体   中英

Cannot read property 'focus' of null error for React-Native-Phone-Input library focus function

I am using react-native-phone-input library for my project. When I used their focus function it worked for the first time, but after that when I type a phone number it gives me a Cannot read property 'focus' of null error.

My code:

 < PhoneInput ref = { (ref) => {ref.focus()}} initialCountry = 'ca' flagStyle = { { width: 50, height: 30, borderWidth: 0, marginLeft: "29%" } } textStyle = { { fontSize: 30, height: 35 } } autoFormat = { true } onChangePhoneNumber = { (number) => this.handleChange(number) } />

SOLUTION:

Please do it like this:

< PhoneInput ref={(ref) => { this.phone = ref; }}

assigning the ref to this.phone.

Now in ComponentDidMount write this.phone.focus() .

REASON:

Refs are not guaranteed to be set when component is Rendering, So you have to use refs in componentDidMount . Whenever you writes something in the inputText, The state changes and it re-renders the component due to which ref is null at that time! So use ref in componentDidMount so it will be called after complete rendering so it will work.

COMPLETE CODE:

componentDidMount=()=>{
    this.phone.focus()
}


<PhoneInput
ref={(ref) => { this.phone = ref; }}
initialCountry = 'ca'
flagStyle = {
  {
    width: 50,
    height: 30,
    borderWidth: 0,
    marginLeft: "29%"
  }
}
textStyle = {
  {
    fontSize: 30,
    height: 35
  }
}
autoFormat = {
  true
}
onChangePhoneNumber = {
  (number) => this.handleChange(number)
}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM