Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native _this2.refs.myinput.focus is not a function

Using React-Native, I have a custom component which extends from TextInput like so:

TextBox.js

...
render() {
  return (
  <TextInput
    {...this.props}
    style={styles.textBox}/>
  );
}
...

MyScene.js (imports TextBox.js)

...
render() {
  render(
    <View>
      <TextBox
        rel='MyFirstInput'
        returnKeyType={'next'}
        onSubmitEditing={(event) => { this.refs.MySecondInput.focus(); }}/>

      <TextBox
        ref='MySecondInput'/>
    </View>
  );
}

When I build the app and press next on the keyboard when focusing on MyFirstInput, I expect MySecondInput to be in focus, instead I get the error:

_this2.refs.MySecondInput.focus is not a function

What could the error be? Is it something to do with the scope of this? Thanks.

like image 453
Pav Sidhu Avatar asked Oct 14 '16 22:10

Pav Sidhu


2 Answers

This is because focus is a method of TextInput, and it is not present in your extended version.

You can add a focus method to TextBox.js as below:

focus() {
    this.refs.textInput.focus();
},

and add a ref to the TextInput

render() {
  return (
  <TextInput
    {...this.props}
    ref={'textInput'}
    style={styles.textBox}/>
  );
}
like image 118
Saleel Avatar answered Nov 01 '22 11:11

Saleel


If you wanted to do this in the modern React Version use

ref = { ref => this._randomName = ref }

If you want to access the method use

this._randomName.anyMethod()
like image 2
Roman Akash Avatar answered Nov 01 '22 11:11

Roman Akash