简单介绍 React Native 整合 Formik 实现表单校验
    		       		warning:
    		            这篇文章距离上次修改已过444天,其中的内容可能已经有所变动。
    		        
        		                
                
import React from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { Formik } from 'formik';
import * as yup from 'yup';
 
// 定义一个简单的表单组件
const MyForm = () => (
  <Formik
    initialValues={{ email: '', password: '' }}
    validationSchema={yup.object().shape({
      email: yup.string()
        .email('Invalid email address')
        .required('Email is required'),
      password: yup.string()
        .min(8, 'Password must be at least 8 characters')
        .required('Password is required'),
    })}
    onSubmit={values => console.log(values)}
  >
    {({ handleSubmit, errors, touched }) => (
      <View style={styles.container}>
        <TextInput
          name="email"
          placeholder="Email"
        />
        {touched.email && errors.email && <Text style={styles.errorText}>{errors.email}</Text>}
        <TextInput
          name="password"
          placeholder="Password"
          secureTextEntry
        />
        {touched.password && errors.password && <Text style={styles.errorText}>{errors.password}</Text>}
        <Button onPress={handleSubmit} title="Submit" />
      </View>
    )}
  </Formik>
);
 
const styles = StyleSheet.create({
  container: {
    // 样式定义
  },
  errorText: {
    color: 'red',
    // 样式定义
  },
});
 
export default MyForm;这个代码实例展示了如何在React Native应用程序中使用Formik库来处理表单数据,并通过yup进行表单验证。代码中定义了一个简单的表单组件,其中包含了电子邮件和密码字段,以及提交按钮。当表单提交时,如果输入的数据不符合验证规则,则会显示错误信息。
评论已关闭