Material UI 自定义文本字段不适用于 Yup

Material UI custom TextField dosn't work with Yup

我正尝试在我的 RegisterForm 中使用我的自定义 TextField 和 Yup,但他不起作用。 每次我都会收到一条消息“⚠ Champ obligatoire”。单击“提交”后,我不明白为什么,但只需简单输入即可。

RegisterPage.js

import React, { useRef } from "react";
import { useForm } from "react-hook-form";
import Button from "../../lib/Button";
import TextField from "../../lib/TextField";
import * as yup from "yup";

const SignupSchema = yup.object().shape({
  firstName: yup.string().required("⚠ Champ obligatoire."),
});

export default function Home() {
  const { register, handleSubmit, errors, watch } = useForm({
    validationSchema: SignupSchema,
  });

  const onSubmit = (data) => console.log(data);
  console.log(errors);

  return (
    <div style={styles.inputForm}>
      <p>Inscription</p>

      <form style={{ marginTop: "40%" }} onSubmit={handleSubmit(onSubmit)}>
        <label style={styles.label} htmlFor="firstName">
          Prénom
        </label>
        <TextField
          style={styles.input}
          name="firstName"
          placeholder="Toto"
          type="text"
          ref={register}
        />
        <br />
        {errors.firstName && (
          <p style={styles.error}>{errors.firstName.message}</p>
        )}
        <br />

        <Button
          style={{ marginTop: 10 }}
          type="submit"
          onClick={handleSubmit(onSubmit)}>
          Termine ton incription
        </Button>
      </form>
    </div>
  );
}

我的自定义文本字段

CustomTextfield.js

import React from "react";
import PropTypes from "prop-types";
import TextField from "@material-ui/core/TextField";

function CustomField({ InputLabelProps = {}, ...props }) {
  return (
    <TextField
      InputLabelProps={{ shrink: true, ...InputLabelProps }}
      {...props}
    />
  );
}

CustomField.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default CustomField;

提前致谢!

您需要在 TextField 上使用 inputRef 而不是 refref 将应用于最外层的元素,即 FormControl 呈现的 div;这对 yup 集成没有任何帮助。 inputRef 会将引用转发给 input 元素。

        <TextField
          style={styles.input}
          name="firstName"
          placeholder="Toto"
          type="text"
          inputRef={register}
        />

相关文档:https://material-ui.com/api/text-field/#props