reactjs React钩形状:用户打字时显示输入内容

gfttwv5a  于 2022-12-26  发布在  React
关注(0)|答案(1)|浏览(177)

我创建了一个React Hook窗体和一个div来显示数据。我想将输入值显示为用户类型。我可以使用onChange来实现这一点,但我在使用react-hook-form时遇到了一个问题。
如果我尝试在{...register()}之后添加onChang e,它会工作,但是如果输入为空,错误消息不会消失。有没有可能的方法来做到这一点?

import "./styles.css";
import { useState } from "react";
import { useForm } from "react-hook-form";

const initalState = {
  name: "test",
  description: "test description"
};

export default function App() {
  const [info, setInfo] = useState(initalState);

  const handleFormSubmit = (data) => {
    setInfo(data);
    console.log(data);
  };

  const handleFormChange = (event) => {
    console.log(event.target.value);
    setInfo({
      ...info,
      [event.target.name]: event.target.value
    });
  };

  return (
    <div className="App">
      <div style={{ textAlign: "left" }}>
        <p>Name: {info.name}</p>
        <p>Description {info.description}</p>
      </div>
      <Form
        handleFormSubmit={handleFormSubmit}
        handleFormChange={handleFormChange}
      />
    </div>
  );
}

const Form = ({ handleFormSubmit, handleFormChange }) => {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();
  return (
    <form onSubmit={handleSubmit(handleFormSubmit)}>
      <label htmlFor="name">Name: </label>
      <input id="name" {...register("name", { required: "Can't be blank" })} />
      <p style={{ color: "red" }}>{errors.name?.message}</p>
      <label htmlFor="description">Description: </label>
      <input
        id="description"
        {...register("description", { required: "Can't be blank" })}
      />
      <p style={{ color: "red" }}>{errors.description?.message}</p>
      <button type="submit">Submit</button>
    </form>
  );
};

fykwrbwg

fykwrbwg1#

订阅可以使用useForms()返回的watch函数,首先将handleFormChange修改为:

const handleFormChange = useCallback(
  (value, name) => {
    setInfo({ ...info, [name]: value[name] });
  },
  [info]
);

然后,在Form组件中,执行以下操作:

const {
  register,
  handleSubmit,
  watch,
  formState: { errors }
} = useForm();

useEffect(() => {
  const subscription = watch((value, { name, type }) => {
    console.log(value, name);
    handleFormChange(value, name);
  });
  return () => subscription.unsubscribe();
}, [watch, handleFormChange]);

相关问题