myT*_*532 2 reactjs react-hook-form
我开始使用它react-hook-form来验证我的输入,但即使我在输入字段中键入/输入某些内容,要求规则也始终会触发。
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input } from "reactstrap";
const setErrorStyle = (name) => {
return {
borderColor: name ? "red" : "",
boxShadow: name ? "0 0 1.5px 1px red" : ""
};
};
const App = () => {
const [comment, setComment] = useState("");
const {
handleSubmit,
control,
formState: { errors }
} = useForm();
const submitForm = (data) => {
console.log(data);
};
return (
<Form onSubmit={handleSubmit(submitForm)}>
<Label for="commentNote" className="mr-sm-10">
Note/Comment
</Label>
<Controller
name="commentNote"
control={control}
defaultValue={comment}
rules={{ required: true }}
render={({ field: { ref, onChange, ...field } }) => (
<Input
{...field}
type="textarea"
rows={5}
id="commentNote"
innerRef={ref}
value={comment}
onChange={(e) => setComment(e.target.value)}
aria-invalid={!!errors.commentNote}
style={setErrorStyle(errors.commentNote)}
/>
)}
/>
{errors.commentNote && (
<span style={{ color: "red" }} role="alert">
required
</span>
)}
<Button type="submit" color="primary" size="sm" className="w-auto">
Submit
</Button>
</Form>
);
};
export default App;
Run Code Online (Sandbox Code Playgroud)
这是用于测试的沙盒:https://codesandbox.io/s/modern-wind-6v2gp
谢谢
原因是因为您正在覆盖表单的状态处理。你实际上所做的就是以这种方式维持你自己的状态。如果您想react-hook-form维持状态,您需要从代码中删除和onChange中的处理:InputuseState
import React from "react";
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input } from "reactstrap";
const setErrorStyle = (name) => {
return {
borderColor: name ? "red" : "",
boxShadow: name ? "0 0 1.5px 1px red" : ""
};
};
const App = () => {
const {
handleSubmit,
control,
formState: { errors }
} = useForm();
const submitForm = (data) => {
console.log(data);
};
return (
<Form onSubmit={handleSubmit(submitForm)}>
<Label for="commentNote" className="mr-sm-10">
Note/Comment
</Label>
<Controller
name="commentNote"
control={control}
rules={{ required: true }}
render={({ field: { ref, ...field } }) => (
<Input
{...field}
type="textarea"
rows={5}
id="commentNote"
innerRef={ref}
aria-invalid={!!errors.commentNote}
style={setErrorStyle(errors.commentNote)}
/>
)}
/>
{errors.commentNote && (
<span style={{ color: "red" }} role="alert">
required
</span>
)}
<Button type="submit" color="primary" size="sm" className="w-auto">
Submit
</Button>
</Form>
);
};
export default App;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12818 次 |
| 最近记录: |