【问题标题】:React Native _this2.refs.myinput.focus is not a functionReact Native _this2.refs.myinput.focus 不是函数
【发布时间】:2017-02-24 10:40:21
【问题描述】:

使用 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的范围有关吗?谢谢。

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    这是因为 focus 是 TextInput 的一种方法,并且在您的扩展版本中不存在。

    您可以向 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()
      

      【讨论】:

        【解决方案3】:

        也许是因为 ref 没有返回 HTML 元素?我认为它与 this 范围没有任何关系,它只是说 .focus 不是一个函数,所以它无法执行可能是因为 .focus 在非 HTML 元素上不存在?

        MDN .focus 表明它必须是一个 HTML 元素,也许您应该记录 ref MySecondInput 并查看是否获得了一个元素?

        【讨论】:

        • 我使用的是 React-Native,但大多数相同的原则都适用。我将this.refs.SecondInput 登录到控制台并返回了我的组件,因此返回了该组件,它只是.focus() 似乎不起作用的函数。
        • 他们在解释 react docs 上的 refs 时实际上实现了一个 .focus() 。看看这个es6 example
        【解决方案4】:

        其他选项是通过 TextBox.js 中的 props 为 TextInput 传递引用。

        MyScene.js(导入 TextBox.js)

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

        TextBox.js

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-14
          相关资源
          最近更新 更多