我是初学者,我正在尝试建立联系表单验证。
import React, {useEffect, useState} from "react";
import {useStep} from "react-hooks-helper";
const Contact: React.FC = (callback, validate) => {
const [contact, setContact] = useState({
name: "",
email: "",
title: "",
content: ""
});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const {index, navigation: {previous, next},} = useStep({steps: 4});
function handleChange(e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) {
const {name, value} = e.target
setContact({...contact, [name]: value})
}
const handleSubmit = (e:React.ChangeEvent<HTMLFormElement>) => {
e.preventDefault();
setErrors(validate(contact));
setIsSubmitting(true);
};
useEffect(() => {
if (Object.keys(errors).length === 0 && isSubmitting) {
callback();
}
}, [errors]);
let errors = {};
if (!contact.email) {
} else if (!/\S+@\S+\.\S+/.test(contact.email)) {
errors.email = "Email address is invalid";
}
return (
<div className="contact">
<div className="contact-inner">
<form onSubmit={handleSubmit}>
{index === 0 && <label>
<input onChange={handleChange} value={contact.name} type="text" name="name"
placeholder="Please enter your name"/>
{errors.email && <p className="error">{errors.email}</p>}
</label>}
{index === 1 && <label htmlFor="email">
<input onChange={handleChange} value={contact.email} type="email" name="email"
placeholder="Please enter your email"/>
</label>}
{index === 2 && <label>
<input onChange={handleChange} value={contact.title} type="text" name="title"
placeholder="Please enter the title"/>
</label>}
{index === 3 && <label>
<textarea onChange={handleChange} value={contact.content} className="content" name="content"
placeholder="Please enter your message"/>
</label>}
</form>
<div className="buttons">
{index === 0 ? <button onClick={previous} disabled>Previous</button> :
<button onClick={previous}>Previous</button>}
{index === 3 ? <button>Submit</button> : <button onClick={next}>Next</button>}
</div>
</div>
</div>
)
}
export default Contact
我在callback()
上收到错误消息:This expression is not callable. Type '{ children?: ReactNode; }' has no call signatures.
[errors]
上的我收到错误:React Hook useEffect缺少依赖项:“回调”和“ isSubmitting”。包括它们或删除依赖项数组。如果“回调”更改过于频繁,请找到定义它的父组件,然后将该定义包装在useCallback中。(react-hooks / exhaustive-deps)
在let errors
上,我得到:无法重新声明块作用域变量“错误”。
在errors.email
上,我得到:属性'email'在类型'{}'上不存在。
请帮助。