android - 如何制作 react native 输入,向用户提供验证状态反馈。 [有效、打印、错误、编辑]

标签 android ios react-native

我想要一个随着用户输入而不断更新然后失去焦点的输入。反馈将是输入周围的边框。

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)

实现此目标的最佳方法是什么?

理想情况下,这将适用于 iOS 和 Android。

最佳答案

TextInput 有两个函数可用于实现此目的:

onBlur onChangeText

要在 TextInput 上动态设置样式,您可以为 bordercolor 附加一个变量,如下所示:

<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);

关于android - 如何制作 react native 输入,向用户提供验证状态反馈。 [有效、打印、错误、编辑],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33962308/

相关文章:

android - Dagger + Kotlin 不注入(inject)

ios - 使用 IOS-Swift 读取 firebase 实时数据库子节点

firebase - 错误: FacebookSDK has not been initialized yet using react native

ios - 如何在 iOS 设备中启用实时重新加载,react-native?

javascript - 如何在 React Native 中呈现原生 UIViewController? (不能只使用 UIView)

android - Web View addJavascriptInterface 问题

android - 在三星 Galaxy Note Edge 上扩展类 android.support.design.widget.AppBarLayout 时出错

android - 如何在android中的文本和下划线之间添加间距?

ios - 在 iTunes 连接中使用旧版本的大应用程序图标

ios - 将应用程序提交到 iTunes Connect 时排除 iPod