简体   繁体   中英

How to create guided user input in React Native?

I would like to create a guided-input user experience using React Native. By that, I mean the following:

  1. User presses TextInput component to search something. The value AND the placeholder is automatically populated with the prefix "ABCDE-"
  2. The user is presented with "numeric" keyboardType . After they enter four numbers, another "-" is automatically added to the search value as such: "ABCDE-1234-"
  3. The user types four more numbers and the final search value looks like so: "ABCDE-1234-5678"

The two aspects of this experience I am curious about are populating prefix "ABCDE-" when onPress , and adding the second dash after n numbers are typed.

Switching between alphabet, alternate characters, and numbers within the same search is quite awkward and cumbersome, and could be simplified this way.

I have made a simple example code like this, you could take it a try and change what you want:

import React, { Component } from "react";
import {TextInput } from "react-native";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { text: '' };
  }

  onChangeTextHandler(text){
    var len = text.length;
    if ((len===5 || len===10)&& len>=this.state.text.length){
      text = text +"-"
    }
    if(text.length!==16){
      this.setState({text:text})
    }    
  }
  render() {
    return (
      <TextInput
      style={{height: 40, borderColor: 'gray', borderWidth: 1,marginTop:20}}
      onChangeText={(text) => this.onChangeTextHandler(text)}
      value={this.state.text}
      placeholder="ABCDE-1234-5678"
    />
    );
  }
}

export default App;

Test Link

for point 1 you can use onFocus prop of TextInput like this

<TextInput
   value={this.state.searchTerm}
   style={/* your style*/}
   onFocus={()=>{
    if(this.state.searchTerm==""){
     this.setState({searchTerm:"ABCDE-"})
    }
  }}
/>

for Point 2 use keyboardType and onChangeText prop of TextInput like this

<TextInput
   value={this.state.searchTerm}
   style={/* your style*/}
   keyboardType={"numeric"}
   onChangeText={(text)=>{
     /*since there 6 characters placed on focus so n character login will be*/

    if(this.state.searchTerm.length>6){         
        if(value.length%5==0){
          let temp = this.state.searchTerm+"-"+text[text.length-1]
          onChangeText(temp)
        } else {
          onChangeText(text)
        }
     }else{
      onChangeText(text)
     }
   }}
   onFocus={()=> {
    if(this.state.searchTerm==""){
      this.setState({searchTerm:"ABCDE-"})
    }
  }}
/>

Hopefully, you will get an idea from this code how to implement guided user input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM