形式提交,反应钩形式和反应状态
我想拥有一个显示“编辑”以输入编辑模式的按钮,并(使用相同的按钮)“保存”以提交表单。
我的问题是,当按钮“编辑”显示时,请按按钮提交提交。
链接到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>
);
}
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.
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>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,表单元素内部的按钮将始终触发提交事件。您可以将按钮给按钮一个“按钮”的类型属性,或在OnClick方法中添加DestrestDefault()以覆盖此属性。
A button inside of a Form element will always fire a Submit event by default. You can give give the button a type attribute of "button", or add a preventDefault() to the onClick method to override this.
尝试这种方法:
and also move your
onClick
condition insidehandleEnterEditMode
methodTry this approach:
and also move your
onClick
condition insidehandleEnterEditMode
method