React Native:如何选择以前的文本输入

Sau*_*til 6 javascript reactjs react-native

我已经定义了代码,专注于下一个TextInput字段

 <View>
     <TextInput
         ref="1"
         maxLength = {1}
         keyboardType={"numeric"}
         onChangeText={(pC1) => this.focusNextField('2',pC1)}
         value={this.state.pC1}
     />
     <TextInput
         ref="2"
         maxLength = {1}
         keyboardType={"numeric"}
         onChangeText={(pC2) => this.focusNextField('3',pC2)}
         value={this.state.pC2}
     />
     <TextInput
          ref="3"
          maxLength = {1}
          keyboardType={"numeric"}
          onChangeText={(pC3) => this.focusNextField('',pC3)}
          value={this.state.pC3}
      /> 
  </View>
Run Code Online (Sandbox Code Playgroud)

以下是为正向传输文本输入光标而编写的函数.但是如何以相反的顺序进行实现.也就是说,按退格键(键盘)

  focusNextField(nextField,pinCode) {
      if(nextField=="2"){
        if(pinCode!=''){
          this.state.pC1=pinCode; // Set value for PC1
          this.refs[nextField].focus();//Goes to TextInput whose ref == 2
        }else{
          this.state.pC1='';
          nextField="1";
          this.refs[nextField].focus();
        }
      }else if(nextField=="3"){
        if(pinCode!=''){
          this.state.pC2=pinCode; // Set value for PC2
          this.refs[nextField].focus();//Goes to TextInput whose ref == 3
        }else{
          this.state.pC2='';
          nextField="2";
          this.refs[nextField].focus();
        }
      }else if(nextField==""){
        if(pinCode!=''){
          this.state.pC3=pinCode; // Set value for PC3
        }else{
          this.state.pC3='';
          nextField="3";
          this.refs[nextField].focus();
        }
      }
    this.forceUpdate(); //Update the Component
  }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我可以从一个向前移动TextInput到另一个.
我的问题是:TextInput如果删除 TextInput数据,如何关注上一个?

Gha*_*chi 0

我假设您正在寻找的行为是:如果输入不为空,则关注下一个(如果有),如果输入为空,则关注上一个(如果有)。我建议您通过声明映射来降低函数的复杂性,如下所示:

focusNextField (currentField, pinCode) {
    const mapping = {
        '1': {
            variable: 'pC1',
            next: '2'
        },
        '2': {
            variable: 'pC2',
            prev: '1',
            next: '3'
        },
        '3': {
            variable: 'pC3',
            prev: '2'
        },
    };
    this.state[mapping[currentField].variable] = pinCode || '';
    if (pinCode) {
        if (mapping[currentField].next) {
            this.refs[mapping[currentField].next].focus();
        }
    } else {
        if (mapping[currentField].prev) {
            this.refs[mapping[currentField].prev].focus();
        }
    }

    this.forceUpdate();
}
Run Code Online (Sandbox Code Playgroud)

您需要在标记中进行的唯一更改是将当前字段而不是下一个字段发送到方法。