【发布时间】:2020-11-16 08:58:26
【问题描述】:
我正在尝试做这样的事情。 当用户单击编辑按钮时,将出现表单字段,用户可以编辑数据。否则用户只能查看数据。 我遇到了麻烦,当用户不想编辑表单并单击取消按钮时,页面开始呈现与页面总表单字段一样多的次数。
在我的原始表单上,我有 80 多个表单字段,当用户单击取消按钮页面时变得非常慢。
当我删除 参考={注册} 从我的页面然后表单不会多次呈现,但表单不会与数据一起提交。 有没有办法停止额外的渲染? 这是我的代码和逻辑。
感谢您的关注。
import React, { useState } from "react";
import { useForm } from "react-hook-form";
function Test() {
const { register, handleSubmit } = useForm();
const [edit, setEdit] = useState(false);
const onSubmit = (data) => {
console.log(data);
};
return (
<div className="App">
<header className="App-header">
{console.log("I am redering.")}
<form onSubmit={handleSubmit(onSubmit)}>
<a
href=""
onClick={(e) => {
setEdit(!edit);
e.preventDefault();
}}
>
{edit ? "Cancel" : "Edit"}
</a>
{edit && (
<p>
<input
type="text"
name="email"
ref={register}
placeholder="Email"
/>
</p>
)}
{edit && (
<p>
<input
type="text"
name="firstname"
ref={register}
placeholder="First Name"
/>
</p>
)}
{edit && (
<p>
<input
type="text"
name="lastname"
ref={register}
placeholder="Last Name"
/>
</p>
)}
{edit && (
<>
<input
type="checkbox"
name="contact[]"
id="contact-one"
value="1"
ref={register}
/>
<label htmlFor="contact-one">One</label>
</>
)}
{edit && (
<>
<input
type="checkbox"
name="contact[]"
id="contact-two"
value="2"
ref={register}
/>
<label htmlFor="contact-two">Two</label>
</>
)}
{edit && <button type="submit">Submit</button>}
{edit === false && (
<>
<p>{`My First Name`}</p>
<p>{`My Last Name`}</p>
<p>{`My Email address`}</p>
<p>{`My Contacts`}</p>
</>
)}
</form>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default Test;
【问题讨论】:
标签: reactjs forms rendering react-hook-form