我想要一个随着用户输入而不断更新然后失去焦点的输入。反馈将是输入周围的边框。
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 有两个函数可用于实现此目的:
要在 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/