gpt4 book ai didi

reactjs - 如何将 Yup 验证架构与 `react-hook-form` 库中的 Controller 组件一起使用

转载 作者:行者123 更新时间:2023-12-04 08:38:01 25 4
gpt4 key购买 nike

  • 我们有一个要使用的第 3 方组件 SecondaryInput
  • 想用Yup验证(不知道如何将 yup 与规则 Prop 一起使用,在 Controller 组件中)
  • 受控组件在子组件内,所以我使用 useFormContext
  • 架构代码不起作用

  • 我的代码是这样的
    注意:我不能在自定义组件中使用 ref,因为它没有像 ref 这样的 Prop
    父组件
      const schema = yup.object().shape({
    patientIdentity: yup.object().shape({
    firstName: yup.string().required('Required field'),
    lastName: yup.string().required('Required field'),
    }),
    });
    const methods = useForm();
    const {
    errors,
    handleSubmit,
    register,
    setValue,
    reset,
    getValues,
    } = useForm({
    defaultValues: {
    patientIdentity: {
    firstName: 'test 1',
    lastName: 'Test 2',
    },
    },
    validationSchema: schema,
    });

    const onSubmit = (data, e) => {
    console.log('onSubmit');
    console.log(data, e);
    };

    const onError = (errors, e) => {
    console.log('onError');
    console.log(errors, e);
    };
    console.log('errors', errors); // Not able to see any any error
    console.log('getValues:> ', getValues()); Not able to see any any values
    return (
    <View style={[t.flex1]}>
    {/* Removed code from here */}
    <View style={[t.flex1, t.selfCenter]}>

    <FormProvider {...methods}>
    <View style={[t.flexCol]}>
    <PatientForm /> // <<Child component
    <PrimaryButton
    style={[t.pL3, t.h10]}
    onPress={handleSubmit(onSubmit, onError)}
    >
    Save changes
    </PrimaryButton>
    </View>
    </FormProvider>
    </Row>
    </View>

    子组件
      const {
    control,
    register,
    getValues,
    setValue,
    errors,
    defaultValuesRef,
    } = useFormContext();

    console.log('errors:>>', errors); // NOt able to log
    console.log('Identity | getValues>', getValues());
    return (
    <DetailCard title="Identity">
    <Controller
    control={control}
    render={(props) => {
    const { onChange, onBlur, value } = props;
    return (
    <SecondaryInput
    label="Legal First Name"
    value={value}
    onTextChange={(value) => onChange(value)}
    onBlur={onBlur}
    />
    );
    }}
    name="patientIdentity.firstName"
    rule={register({
    required: ' name cannot be empty',
    })}
    defaultValue=""
    />
    <Controller
    control={control}
    as={({ onChange, onBlur, value }) => {
    return (
    <SecondaryInput
    label="Legal Last Name"
    value={value}
    onTextChange={(value) => onChange(value)}
    onBlur={onBlur}
    />
    );
    }}
    name="patientIdentity.lastName"
    rules={{
    required: 'this is required field',
    message: 'required field',
    }}
    defaultValue=""
    />
    </DetailCard>
    )

    最佳答案

    您需要检查以下几点:

  • schema object 不依赖于任何局部范围的变量。你可以把它放在函数之外,这样组件就不会在每次渲染时重新创建它
  • 通过是的schema反对 yupResolver首先而不是直接传递给 resolver

  • import React from 'react';
    import { useForm } from 'react-hook-form';
    import { yupResolver } from '@hookform/resolvers/yup';
    import * as yup from "yup";

    const schema = yup.object().shape({
    patientIdentity: yup.object().shape({
    firstName: yup.string().required('Required field'),
    lastName: yup.string().required('Required field'),
    }),
    });

    const App = () => {
    const { ... } = useForm({
    resolver: yupResolver(schema),
    });

    return (...);
    };
  • 如果您使用第三方库编写验证规则,例如 Yup ,您可以删除 rules Prop 来自Controller因为它们是重复的。
  • 关于reactjs - 如何将 Yup 验证架构与 `react-hook-form` 库中的 Controller 组件一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64705996/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com