我正在使用 tcomb-form-native 并且能够在单击登录按钮时禁用错误消息。同样在单击登录按钮时,我将其路由到下一页,即主页。如果必填字段为空,我想禁用登录按钮并启用它并在两个字段都填满时重定向到主页。下面是我尝试过的代码。
import React, { Component } from 'react';
import {
AppRegistry,
Text,
Image,
View,
Button,
StyleSheet,
TextInput,
Linking,
Alert,
Navigator
} from 'react-native';
import t from 'tcomb-form-native';
const Form = t.form.Form;
// here we are: define your domain model
const Email = t.subtype(t.Str, (email) => {
const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
});
const LoginFields = t.struct({
username: Email, // a required string
password: t.String, // a required string
});
const options = {
fields: {
password: {
type: 'password',
placeholder: 'Password',
error: 'Password cannot be empty'
},
username: {
placeholder: 'e.g: abc@gmail.com',
error: 'Insert a valid email'
}
}
}; // optional rendering options (see documentation)
export default class Login extends Component {
_onSubmit() {
const value = this.refs.form.getValue();
if (value) { // if validation fails, value will be null
console.log(value);
// value here is an instance of LoginFields
}
this.props.navigator.push({
id: 'Home'
});
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
</View>
<View style={styles.content}>
<Text style={styles.contentHeader}>
Pateast Login
</Text>
<View style={styles.loginFormContent}>
<Form
ref="form"
type={LoginFields}
options={options}
/>
<Text style={{color: 'blue', marginBottom: 10}}
onPress={() => Linking.openURL('https://www.google.co.in')}>
Forgot Password?
</Text>
<Button
onPress={this._onSubmit.bind(this)}
title="Login"
color="#008080"
accessibilityLabel="Ok, Great!"
/>
</View>
</View>
<View style={styles.footer}>
</View>
</View>
);
}
}
const styles = StyleSheet.create(
{
container: {
flex: 1
},
contentHeader: {
fontFamily: 'sans-serif-condensed',
fontWeight: 'bold',
fontSize: 40,
alignSelf: 'center',
marginBottom: 30
},
header : {
flex: 0.5,
backgroundColor: '#008080'
},
content: {
flex: 10,
backgroundColor: '#f8f8ff',
justifyContent: 'center'
},
loginFormContent: {
marginHorizontal: 20
},
footer: {
flex: 0.5,
backgroundColor: '#008080'
},
loginText: {
fontSize: 20,
marginBottom: 10
},
inputFields: {
fontSize: 20,
borderStyle: 'solid',
borderColor: '#000000',
borderRadius: 30,
marginBottom: 10
}
}
)