import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, TextInput, View, Button, SafeAreaView, Dimensions } from 'react-native';
import { Formik } from 'formik';
const screenWidth = Dimensions.get('screen').width;
export default function App() {
const [useInfo, setUseInfo] = useState({
name: '',
email: '',
phone: '',
});
const validate = (values) => {
const errors = {};
if (!values.name) {
errors.name = 'Required';
} else if (!/^[\u4e00-\u9fa5]{2,15}$/u.test(values.name)) {
errors.name = 'Invalid name';
}
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
}
if (!values.phone) {
errors.phone = 'Required';
} else if (!/^[0-9]{10}$/i.test(values.phone)) {
errors.phone = 'Invalid phone number';
}
return errors;
};
const MyReactNativeForm = () => {
return (
<Formik
initialValues={{ name: '', email: '', phone: '' }}
validate={validate}
onSubmit={(values) => console.log(values)}
>
{({
handleChange,
handleBlur,
handleSubmit,
values,
errors,
touched,
}) => (
<View style={{ flex: 1 }}>
<TextInput
onChangeText={handleChange('name')}
onBlur={handleBlur('name')}
value={values.name}
style={styles.input}
/>
{touched && touched.name && errors.name && (
<Text style={{ color: 'red' }}>{errors.name}</Text>
)}
<TextInput
onChangeText={handleChange('email')}
onBlur={handleBlur('email')}
value={values.email}
style={styles.input}
/>
{touched && touched.email && errors.email && (
<Text style={{ color: 'red' }}>{errors.email}</Text>
)}
<TextInput
onChangeText={handleChange('phone')}
onBlur={handleBlur('phone')}
value={values.phone}
style={styles.input}
/>
{touched && touched.phone && errors.phone && (
<Text style={{ color: 'red' }}>{errors.phone}</Text>
)}
<Button onPress={handleSubmit} title="Submit" style={styles.button} />
</View>
)}
</Formik>
);
};
useEffect(() => {
console.log(useInfo);
}, [useInfo]);
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<Text style={{ fontSize: 20, fontWeight: 'bold', color: 'black' }}>
Formik
</Text>
<MyReactNativeForm />
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
},
input: {
margin: 10,
padding: 10,
borderWidth: 1,
height: 40,
width: screenWidth - 40,
},
button: {
margin: 10,
padding: 10,
backgroundColor: 'blue',
height: 40,
},
});
网友评论