【问题标题】:Focus on next form Input using focus() function使用 focus() 函数关注下一个表单输入
【发布时间】:2018-10-21 08:03:13
【问题描述】:

我正在使用带有 react native 的 typescript,我不知道我是否正确定义了我的输入引用类型。

这是我代码的相关部分:(两个组件都是我的自定义组件,TextInput 不适用于 react-native。)

// in begin of class
private readonly passwordInputRef: React.RefObject<Password> = createRef();

// in render function
<TextInput
    key={'login page username'}
    language={language}
    placeholder={'Username:'}
    value={username}
    containerStyle={styles.username}
    hasError={loginError}
    onChangeText={this.setUsername}
    returnKeyType={"next"}
    blurOnSubmit={false}
    onSubmitEditing={() => this.passwordInputRef.current!.focus()} />
<Password
    key={'login page password'}
    ref={this.passwordInputRef}
    language={language}
    placeholder={'Password:'}
    value={password}
    containerStyle={styles.password}
    hasError={loginError}
    onChangeText={this.setPassword}/>

当我运行应用程序并按下键盘上的下一步按钮时,它给了我一个错误_this.passwordInputRef.current.focus is not a function

我在 stackoverflow 上搜索并阅读了许多答案,但没有一个没有解释它是如何与 typescript 一起工作的。

我也读过这个issue on github,似乎我的代码与那个非常相似,除了我使用的是打字稿,所以我认为我对passwordInputRef的定义命令有问题。

我做错了什么?

目前我正在使用:

"react": "16.5.2"
"react-native": "0.55.2"

【问题讨论】:

    标签: typescript react-native


    【解决方案1】:

    我解决了我的问题。在Password 组件类中,我定义了一个带有 react-native TextInput 类型的 ref 对象,

    // in begin of Password class
    private readonly inputRef: React.RefObject<TextInput> = createRef();
    

    然后在render方法中将此引用对象设置为内部TextInput:

    // other views
    <TextInput
        {...this.props}
        ref={this.inputRef} <----
        key={'password value input'}
        secureTextEntry={hidePassword}
        />
    // other views
    

    并为类定义一个focus 方法,如下所示:

    public focus() {
      this.inputRef.current && this.inputRef.current.focus();
    }
    

    无需更改任何其他内容,完美运行。

    如果我理解正确,程序应该如下:

    • 当您自定义输入时,您需要自己处理焦点。
    • 我问题中的代码,调用Password组件的focus方法
    • 我必须将焦点转移到我的内部输入组件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2013-11-16
      • 2013-03-13
      相关资源
      最近更新 更多