2015-11-27 35 views
4

我想有一個輸入,不斷更新,隨着用戶鍵入,然後失去焦點。反饋將是輸入的邊界。如何做出反應原生輸入,爲用戶提供驗證狀態反饋。 [有效,Printine,錯誤,編輯]

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。

回答

7

的TextInput有兩個功能,這將是實現這一有用:

onBluronChangeText

動態設置中TextInput的風格,您可以附加一個變量如下面的BORDERCOLOR :

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

然後,將結果從onChangeText函數通過ar egex或模式匹配器來實現您嘗試實現的任何結果。

我在這裏設置了一個工作項目,檢查是否有空白,並拋出你想要的錯誤。你可以把它編輯成更具體的你的需求,但基本前提應該是一樣的。我還將下面的代碼放在實現該功能的工作項目中:

'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); 
+1

此鏈接已中斷.. https://rnplay.org/apps/3ac_ig –

相關問題