简体   繁体   English

React 中的表单提交、react-hook-form 和 state

[英]Form submission, react-hook-form and state in React

I would like to have a button that displays "Edit" to enter Edit mode and (using the same button) "Save" to submit the form.我想要一个显示“编辑”的按钮以进入编辑模式,并(使用相同的按钮)“保存”以提交表单。

My problem is that it already submits the form upon pressing the button while the button text "Edit" is showing.我的问题是它已经在显示按钮文本“编辑”时按下按钮提交表单。

Link to codesandbox , containing the code below. 链接到 codesandbox ,包含以下代码。

import "./styles.css";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@material-ui/core";

export default function App() {
  //Setting up state
  const [isEditing, setIsEditing] = useState(false);

  //Handler for entering edit mode.
  const handleEnterEditMode = () => {
    setIsEditing(true);
    console.log("Edit mode entered.");
  };

  //Handler that runs on form submission.
  const handleSave = () => {
    console.log("Form submitted.");
  };

  //Setting up some react-hook-forms variables according to their docs
  const {
    register,
    formState: { errors },
    handleSubmit,
    control,
    reset
  } = useForm();

  //In render:

  return (
    <div className="App">
      <form noValidate onSubmit={handleSubmit(handleSave)}>
        <Button
          {...(isEditing ? { type: "submit" } : {})}
          {...(!isEditing ? { onClick: handleEnterEditMode } : {})}
        >
          {!isEditing ? "Edit" : "Save"}
        </Button>
      </form>
    </div>
  );
}

A button inside of a Form element will always fire a Submit event by default.默认情况下,Form 元素内的按钮将始终触发 Submit 事件。 You can give give the button a type attribute of "button", or add a preventDefault() to the onClick method to override this.你可以给按钮一个“按钮”的类型属性,或者在 onClick 方法中添加一个 preventDefault() 来覆盖它。

Try this approach:试试这个方法:

 < Button type = { isSubmiting ? "submit" : null } > {!isEditing ? "Edit" : "Save" } </Button>
and also move your onClick condition inside handleEnterEditMode method 并在handleEnterEditMode方法中移动你的onClick条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM