React Native _this2.refs.myinput.focus is not a function:React Native中_this2.refs.myinput.focus不是一个函数。

10

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

TextBox.js

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

MyScene.js(导入TextBox.js)

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

      <TextBox
        ref='MySecondInput'/>
    </View>
  );
}
当我构建应用并在聚焦于MyFirstInput时按下键盘上的"下一个",我期望MySecondInput将处于聚焦状态,但我得到了错误提示:
_this2.refs.MySecondInput.focus is not a function

错误可能是什么?是否与 this 的范围有关?谢谢。

4个回答

17
这是因为 focus 是 TextInput 的一种方法,在你扩展的版本中不存在。
您可以按照以下方式将 focus 方法添加到 TextBox.js:
focus() {
    this.refs.textInput.focus();
},

并在 TextInput 中添加一个引用

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

2
如果您想在现代的React版本中实现此功能,可以使用以下方法:
ref = { ref => this._randomName = ref }

如果您想访问该方法,请使用

this._randomName.anyMethod()

0
也许是因为ref没有返回HTML元素?我认为这与this作用域无关,它只是说.focus不是一个函数,所以不能执行,可能是因为在非HTML元素上不存在.focus? MDN .focus显示它必须是一个HTML元素,也许你应该记录ref MySecondInput并查看是否获得了一个元素?

我正在使用React-Native,但大部分原则都适用。 我将 this.refs.SecondInput 记录到控制台中,返回了我的组件,因此组件是可用的,只是 .focus() 函数似乎无法正常工作。 - Pav Sidhu
实际上,在React文档中讲解refs时,他们实现了一个.focus()。看一下这个es6示例 - Kevin

0

另一个选择是通过 props 从 TextBox.js 将引用传递给 TextInput。

MyScene.js(导入 TextBox.js)

<TextBox      
 refName={ref => { this.MySecondInput = ref; }}
/>

TextBox.js

 <TextInput
    {...this.props}
    ref={this.props.refName}
    ... />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接