所以,我有一个自定义的Input组件,它是用react-hooks-form创建的。它可以有一个初始值,如果它有这样的属性。在主窗体中,我获取数据并将其设置为状态。我想把这个状态作为一个属性传递给输入,但是它不起作用,有时一个值是未定义的,有时它有一个值,但是它不设置输入的值。输入代码:
const Input = ({register, name, label, errors, initialValue}) => {
const {setValue} = useForm();
useEffect(() => {
setValue(name, initialValue)
}, [initialValue, name, setValue])
return (
<div className={`input`} >
<label>{label}</label>
<input
{...register(name, {required: "This field is required!", minLength:{
value: 5,
message: "The field must be at least 5 characters"
}})}
/>
{errors[name] && <span>{errors[name].message}</span>}
</div>
);
};
获取数据的窗体代码:
const FormTest = (props) => {
const {register, handleSubmit, formState: {errors}} = useForm();
const [title, setTitle] = useState();
const [description, setDescription] = useState();
const onSubmit = (data) => {
console.log(data)
}
useEffect(() => {
let random = Math.floor(Math.random() * 100) + 1;
const fetchData = async () => {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${random}`);
const data = await response.json();
setTitle(data.title);
setDescription(data.body);
}
fetchData();
}, []);
return (
<div className="form-wrapper">
<h2 className="form-header">TEST</h2>
<form onSubmit={handleSubmit(onSubmit)}>
<Input
name="title"
label="Title"
register={register}
errors={errors}
initialValue={title}
/>
<Input
name="description"
label="description"
register={register}
errors={errors}
initialValue={description}
/>
<input type="submit"/>
</form>
</div>
);
}
1条答案
按热度按时间xurqigkl1#
我在你的代码中看不到
handleSubmit
函数。您已经调用了handleSubmit并将onSubmit作为参数传递给该函数。所以我认为问题就在这里