[英]Listen to Formik values changes
我想要重用的组件中有一个 formik 表单。 为此,我需要监听表单值的变化,以便调用两个函数, getFormValues
和getFormErrors
,这两个函数将由父组件传递:
import React from "react";
import * as Yup from 'yup';
import { Formik } from 'formik';
import CheckBox from "@react-native-community/checkbox";
import { Text, TextInput } from "react-native";
import { errorStyle } from "../../styles/form.styles";
export default function UserCredentialForm({getFormValues, getFormErrors}) {
const formSchema = Yup.object().shape({
email: Yup.string().email()
.required('Required'),
password: Yup.string()
.test('lenght', 'min 5chr max 10chr', (val = '') => val.length > 4 && val.length < 11)
.required('Required'),
});
const [state, setState] = React.useState({
form: {
email: '',
password: '',
}
});
const formRef = React.useRef({} as any);
React.useEffect(() => {
console.log('formref', formRef.current.values);
getFormValues(formRef.current.values);
getFormErrors(formRef.current.errors);
}, [formRef.current.values, formRef.current.errors]);
return (
<Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => {}}>
{({ handleChange, values, touched, errors }) => (
<React.Fragment>
{errors.password && touched.password ? <Text>{errors.email}</Text> : null}
<TextInput
style={errors.email && touched.email ? errorStyle.input : null}
keyboardType='email-address'
onChangeText={handleChange('email')}
value={values.email}
placeholder="email"
/>
{errors.password && touched.password ? <Text>{errors.password}</Text> : null}
<TextInput
style={errors.password && touched.password ? errorStyle.input : null}
onChangeText={handleChange('password')}
value={values.password}
placeholder="password"
secureTextEntry={true}
/>
</React.Fragment>
)}
</Formik>
);
}
如您所见,我正在使用链接到表单参考值的useEffect
挂钩,但它在表单首次渲染时仅被调用一次。 我错过了什么? 如何订阅所有值更改?
使用useFormikContext
挂钩获取值。 您不应该在 useEffect 中使用 ref,因为改变ref.current
不会触发渲染。 这是useFormikContext
钩子的实现
这里有一个解决方案:
https://stackoverflow.com/a/56269090/752636
我需要在表单内移动我的钩子
<Formik
initialValues={initialValues}
...
>
{props => {
getFormErrors(props.errors); // store values in state 'formValues'
getFormValues(props.values); // or use any function to get values like this
return (
<form onSubmit={props.handleSubmit}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.