How to make a response native input, which gives the user the status of validation. [Valid, Printine, Error, Editing]

I would like to have an input that is constantly updated as the user enters and then loses focus. Feedback will be the border around the input.

1 Green: when valid
2 Amber: when typing and is in error state (Green when valid)
3 Red: when in error state and unfocused
4 Nothing: when input is pristine (not touched and empty)

What is the best way to achieve this?

Ideally, this will work with both iOS and Android.

+4
source share
1 answer

TextInput has two functions that will be useful for this:

onBlur and onChangeText

To dynamically set the style in TextInput, you can attach a variable to bordercolor, as shown below:

<TextInput
  onBlur={ () => this.onBlur() }
  onChangeText={ (text) => this.onChange(text) }
  style={{ borderColor: this.state.inputBorder, height: 70, backgroundColor: "#ededed", borderWidth: 1 }} />

onChangeText , .

, , , , . , , . , :

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput
} = React;

var SampleApp = React.createClass({

  getInitialState: function() {
    return {
        inputBorder: '#eded',
      defaultVal: ''
    }
  },

  onBlur: function() {
    console.log('this.state.defaultVal', this.state.defaultVal)
    if(this.state.defaultVal.indexOf(' ') >= 0) {
        this.setState({
        inputBorder: 'red'
      })
    }
  },

  onChange: function(text) {
    this.setState({
        defaultVal: text
    })
    if(text.indexOf(' ') >= 0) {
        this.setState({
        inputBorder: '##FFC200'
      })
    } else {
        this.setState({
        inputBorder: 'green'
      })
    }
  },

  render: function() {
    return (
      <View style={styles.container}>
        <View style={{marginTop:100}}>
            <TextInput
            onBlur={ () => this.onBlur() }
            onChangeText={ (text) => this.onChange(text) }
            style={{ height: 70, backgroundColor: "#ededed", borderWidth: 1, borderColor: this.state.inputBorder }} />
        </View>
        <View style={{marginTop:30}}>
            <TextInput 
          style={{ height: 70, backgroundColor: "#ededed" }} />
        </View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,  
  }
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);
+7

Source: https://habr.com/ru/post/1617774/


All Articles