聆听福米克价值观的变化

Nem*_*mus 5 reactjs formik react-hooks

我在组件中有一个 formik 表单,我想重用它。为此,我需要监听表单值的更改,以便调用两个函数getFormValuesgetFormErrors,这两个函数将由父组件传递:

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我使用useEffect链接到表单引用值的钩子,但它仅在表单首次渲染时被调用一次。我缺少什么?我如何订阅所有值更改?

Nem*_*mus 5

这里有一个解决方案:

/sf/answers/3938836331/

我需要在表单内移动我的钩子

<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}>
Run Code Online (Sandbox Code Playgroud)


小智 2

使用useFormikContext钩子来获取值。您不应该在 useEffect 中使用 ref 因为改变ref.current不会触发渲染。useFormikContext这里是hook的实现

https://formik.org/docs/api/useFormikContext

  • useFormikContext 从父母到孩子工作,我需要一些东西来从孩子到父母进行沟通 (2认同)