【发布时间】:2022-08-04 16:34:22
【问题描述】:
我的输入中有变量错误的问题。
我添加到接口error?: string,为什么打字稿告诉我这个通信?
Type \'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>> | undefined\' is not assignable to type \'string | undefined\'.
Type \'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>>\' is not assignable to type \'string\'.ts(2322)
Input.tsx(6, 3): The expected type comes from property \'error\' which is declared here on type \'IntrinsicAttributes & InputProps\'
波纹管代码:
用法.tsx
import { yupResolver } from \"@hookform/resolvers/yup\";
import { useForm } from \"react-hook-form\";
import * as yup from \"yup\";
import Form from \"./Form\";
import Input from \"./Input\";
// interface for form
interface EmailInterface {
email: string;
password: string;
}
// validation
const EmailSchema = yup.object().shape({
email: yup
.string()
.email(\"Enter a valid email\")
.required(\"Email is required\"),
password: yup
.string()
.max(32, \"Max password length is 32\")
.required(\"Password is required\")
.matches(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*])(?=.{8,})/,
\"Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and One Special Case Character\"
),
secret: yup
.string()
.min(128, \"Minimum legnth is 4\")
.max(32, \"Max password length is 32\")
.required(\"Password is required\"),
});
const Usage = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({ resolver: yupResolver(EmailSchema) });
const onSubmit = (data: EmailInterface) => console.log(data);
return (
<Form
buttonLabel=\"Change Email\"
register={register}
handleSubmit={handleSubmit}
onSubmit={onSubmit}
className=\"change-form\"
>
<Input
name=\"email\"
type=\"email\"
placeholder=\"Enter your email\"
error={errors.email?.message}
autoFocus
/>
<Input
name=\"password\"
type=\"password\"
placeholder=\"Password\"
error={errors.password?.message}
/>
<Input
name=\"secret\"
type=\"secret\"
placeholder=\"secret\"
error={errors.secret?.message}
/>
</Form>
);
};
export default Usage;
输入.tsx
import { FC, InputHTMLAttributes } from \"react\";
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
name: string;
label?: string;
error?: string;
register?: any;
wrapperClass?: string;
className?: string;
}
const Input: FC<InputProps> = ({
register,
name,
error,
label,
wrapperClass,
...rest
}) => {
return (
<div className={wrapperClass}>
{label && <label htmlFor={name}>{label}</label>}
<input
aria-invalid={error ? \"true\" : \"false\"}
{...register(name)}
{...rest}
/>
{error && <span role=\"alert\">{error}</span>}
</div>
);
};
export default Input;
标签: reactjs