使用React钩子表单进行表单验证

时间:2020-06-24 05:56:56

标签: reactjs react-hooks react-hook-form

我想在调用onClick函数之前验证表单。我已经使用react-hook-form组件来实现表单验证。但是,它似乎不起作用。即使当表单为空时,如果我单击按钮,也会创建一个空组件。

我是一个初学者,可以做出反应。 该项目来自Udemy课程,我想进行一些改进,即表单验证。

import React, { useState } from "react";
import AddIcon from "@material-ui/icons/Add";
import Fab from "@material-ui/core/Fab";
import Zoom from "@material-ui/core/Zoom";
import { useForm } from "react-hook-form";

function CreateArea(props) {

  const { register, handleSubmit, errors } = useForm();
  const onSubmit = data => {
    console.log(data);
  };

  const [createNote, setCreateNote] = useState({
    title: "",
    content: "",
  });

  const [isExpanded, setIsExpanded] = useState(false);

  
  function updateChange(event) {
    const { name, value } = event.target;
    setCreateNote((prevNote) => {
      return {
        ...prevNote,
        [name]: value,
      };
    });
  }

  function submitNote(event) {
    props.onAdd(createNote);
    setCreateNote({
      title: "",
      content: "",
    });
    event.preventDefault();
  }

  function expand(){
    setIsExpanded(true);
  }

  return (
    
    <div>
      <form onSubmit={handleSubmit(onSubmit)} className="create-note" >
        {isExpanded && <input
          onChange={updateChange}
          value={createNote.title}
          name="title"
          placeholder="Title"
          ref={register({ required: true ,maxLength: 15 })}
        />}
        {errors.title && <p>Title is required</p>}

        <textarea
          onClick={expand}
          onChange={updateChange}
          value={createNote.content}
          name="content"
          placeholder="Take a note..."
          rows={isExpanded ? "3" : "1"}
          ref={register({ required: true })}
        />
        {errors.content && <p>Content is required</p>}
        
        <Zoom in={isExpanded}>
          <Fab type="submit" onClick={submitNote}>
            <AddIcon />
          </Fab>
        </Zoom>

      </form>
    </div>
  );
}

export default CreateArea;

1 个答案:

答案 0 :(得分:1)

我不确定我是否完全理解该问题,但是如果您想在 expand 函数中验证表单,并根据其是否有效采取行动,请对表单进行响应具有 triggerValidation 函数,该函数为此目的返回一个承诺。

const { triggerValidation } = useForm();

function expand() {
    triggerValidation().then(valid => {
        if (valid) {
            setIsExpanded(true);
        }
    });
}