如何处理子组件的 YUP 验证 (ReactJS)

如何解决如何处理子组件的 YUP 验证 (ReactJS)

我正在使用 reactjs 和 lib unform 来处理我的应用程序的注册表结构。我需要用动态输入做一个更复杂的结构,然后,我做了一个分离的组件来使代码更有条理,到目前为止一切都很好,但是当我用 yup 进行验证时,我注意到子组件的字段没有得到我认为会得到的错误

有没有人知道一个聪明的解决方案?

结果:只有主组件的字段有验证错误

See the image

这里是主窗体结构的代码

const CadastroAdvF3: React.FC = () => {

  const { addToast } = usetoast();

  const formRef = useRef<FormHandles>(null);

  const handleSubmit = useCallback(
    async data => {

      formRef.current?.setErrors({});

      try {

       // validation

        const schema = Yup.object().shape({
          professionalDescription: Yup.string()
            .required('Descrição profissional obrigatória')
            .min(
              300,'A descrição profissional deve ter no mínimo 300 caracteres.'
            ),// the following itens are inside the react component formationArea
          // and professionalExperience.

          institution: Yup.string().required('Instituição Obrigatória'),course: Yup.string().required('Curso Obrigatório'),from: Yup.string().required('Data Obrigatória'),until: Yup.string().required('Data Obrigatória'),role: Yup.string().required('Cargo Obrigatório'),business: Yup.string().required('Empresa/Instituição Obrigatória')
        });

        await schema.validate(data,{
          abortEarly: false
        });

        addToast({
          title: 'Informações regisTradas com sucesso.',type: 'success'
        });
      } catch (error) {
        const errors = getValidationErrors(error);
        formRef.current?.setErrors(errors);
      }
    },[addToast]
  );

  return (
    <Styled.Container>
      
      <Styled.Content>
        <Styled.Form>
          <h3>Formulário</h3>

          <Form
            ref={formRef}
            onSubmit={data => {
              handleSubmit(data);
            }}
          >
            {/* <div className="twoColumns">
              <Input row name="firstName" placeholder="Nome" />
              <Input row name="lastName" placeholder="Sobrenome" />
            </div> */}
            <Input label="Foto de Perfil" name="profilePhoto" type="file" />
            <TextArea
              name="professionalDescription"
              label="Descrição Profissional"
              placeholder="Sua descrição profissional..."
            />


            <FormationArea />

            <ProfessionalExperience />

            <SuperButton type="submit">Próximo</SuperButton>
          </Form>
        </Styled.Form>
      </Styled.Content>
    </Styled.Container>
  );
};

export default CadastroAdvF3;

以及 FormationArea 组件的结构示例:

const FormationArea: React.FC = () => {

  // ...

  return (
    <context.Provider value={{ handleRemoveFormationArea }}>
      <Styled.Container>
        <div className="header">
          <h3>Formação</h3>
          <button type="button" onClick={handleAddFormationArea}>
            Adicionar Instituição
          </button>
        </div>
        {formationAreaFields.map((formationAreaFields,index) => {
          return <Item key={index} Pkey={index} />;
        })}
      </Styled.Container>
    </context.Provider>
  );
};

 // above the component that is rendered in the formation area

const Item: React.FC<KeyComponentProp> = ({ Pkey }) => {

 // ....

  return (
    <CourseAreasContext.Provider
      value={{ handleRemoveCourseArea,handleAddCourseArea }}
    >
      <div className="item">
        <Scope path={`formation[${Pkey}]`}>
          {/* <h4>Instituição</h4> */}
          <Styled.PersonalizedColumnsFormation>
            <Input
              label="Instituição"
              name="institution"
              placeholder="Instituição"
            />
            {Pkey > 0 && (
              <button
                type="button"
                onClick={() => handleRemoveFormationArea(Pkey)}
              >
                <TiTrash size={23} />
              </button>
            )}
          </Styled.PersonalizedColumnsFormation>
          {CourseAreaFields.map((course,index) => {
            return <DownScopeAreas key={index} Pkey={index} />;
          })}
        </Scope>
      </div>
    </CourseAreasContext.Provider>
  );
};

export default FormationArea;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?