代码之家  ›  专栏  ›  技术社区  ›  Saeed Zhiany

使用focus()函数关注下一个表单输入

  •  0
  • Saeed Zhiany  · 技术社区  · 7 年前

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

    下面是我的代码的相关部分:(这两个组件都是我的自定义组件, 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 ,似乎我的代码与此非常相似,但我使用的是typescript,所以我认为我的define命令有问题 passwordInputRef .

    我做错了什么?

    目前我正在使用:

    "react": "16.5.2"
    "react-native": "0.55.2"
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Saeed Zhiany    7 年前

    我解决了我的问题。在里面 Password 组件类I使用react native定义引用对象 TextInput 类型,

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

    然后在呈现方法中将此引用对象设置为内部文本输入:

    // 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();
    }
    

    不需要改变任何其他东西,它工作得很好。

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

    • 当您自定义输入时,您需要自己处理焦点。
    • 我要问的代码,打电话 集中 方法 密码 成分
    • 我必须将焦点转移到我的内部输入组件
    推荐文章