我正在尝试使用YUP验证material-ui-phone-number
字段,但是当我对组件YUP拥有inputRef属性时,会触发一个错误,提示TypeError: e is undefined
。
似乎material-ui-phone-number
组件正在发送该值,而YUP期待一个事件(e.target.value
)
这是我的代码:
import React, { useState } from "react";
import MuiPhoneNumber from "material-ui-phone-number";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers";
import * as yup from "yup";
const Step1Schema = yup.object().shape({
name: yup.string().required("O campo nome é obrigatório"),
email: yup
.string()
.required("O campo email é obrigatório")
.email("Formato de email inválido"),
phone: yup.mixed().test((value) => console.log(value))
});
const Step1 = ({ formData, nextStep, formStepData }) => {
const { register, handleSubmit, errors } = useForm({
resolver: yupResolver(Step1Schema)
});
const onSubmit = async (data) => {
console.log(data);
};
const [phone, setPhone] = useState("");
return (
<div data-aos="fade-up" id="house-form">
<form onSubmit={handleSubmit(onSubmit)}>
<MuiPhoneNumber
id="contactPhoneNumber"
inputRef={register}
defaultCountry={"pt"}
style={{ width: "100%" }}
name="phone"
label="Contacto telefónico"
variant="outlined"
margin="normal"
value={phone}
onChange={(value) => setPhone(value)}
error={Boolean(errors.phone)}
/>
</form>
</div>
);
};
export default Step1;
答案 0 :(得分:1)
您始终可以使用Controller
组件与react-hook-form
不能立即使用的任何第三方输入组件进行集成。
const { control, ... } = useForm();
...
<Controller
name="phone"
control={control}
render={({ name, onBlur, onChange, value }) => (
<MuiPhoneNumber
name={name}
value={value}
onBlur={onBlur}
// onChange pass the raw value so you can access it using e instead of
// e.target.value. props.onChange can accept the value directly
onChange={onChange}
{...}
/>
)}
/>