React Native _this2.refs.myinput.focus不是一个函数

Pav*_*dhu 9 javascript ecmascript-6 reactjs react-native

使用React-Native,我有一个从TextInput扩展的自定义组件,如下所示:

TextBox.js

...
render() {
  return (
  <TextInput
    {...this.props}
    style={styles.textBox}/>
  );
}
...
Run Code Online (Sandbox Code Playgroud)

MyScene.js(导入TextBox.js)

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

      <TextBox
        ref='MySecondInput'/>
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

当我构建应用程序并在关注时按下键盘上的下一个MyFirstInput,我希望MySecondInput成为焦点,而我得到错误:

_this2.refs.MySecondInput.focus is not a function
Run Code Online (Sandbox Code Playgroud)

错误是什么?这与范围有关this吗?谢谢.

小智 14

这是因为focus是TextInput的一种方法,它在扩展版本中不存在.

您可以将焦点方法添加到TextBox.js,如下所示:

focus() {
    this.refs.textInput.focus();
},
Run Code Online (Sandbox Code Playgroud)

并为TextInput添加一个引用

render() {
  return (
  <TextInput
    {...this.props}
    ref={'textInput'}
    style={styles.textBox}/>
  );
}
Run Code Online (Sandbox Code Playgroud)