简体   繁体   English

React:使用相同的表单创建和更新记录

[英]React: Using the same form for create and update record

I am new in ReactJS and build a Create form for record.我是 ReactJS 的新人,建了一个 Create 表单来记录。 On the other hand, now I need to create an Update form and I am wondering an elegant solution and apply it for the next projects as well.另一方面,现在我需要创建一个更新表单,我想知道一个优雅的解决方案并将其应用于下一个项目。

I checked several projects and examples, but could not be sure regarding the following issues:我检查了几个项目和示例,但无法确定以下问题:

1. Can I use the same form for Create and Update? 1.我可以使用相同的表格来创建和更新吗? Is there a proper example for that?有一个合适的例子吗?

2. When using Update form, I thought passing the record to Update form via props and then populate these values to the related controls. 2.在使用Update form 的时候,我想通过props 将记录传递给Update form,然后将这些值填充到相关的控件中。 The rest seems to be similar to Create form, right? rest 好像和Create form差不多吧? Or is there a specific approach for this purpose?或者是否有用于此目的的特定方法?

3. How can I pass record as prop to the Update form (I open it via Route, then should I pass a query param, etc?) 3.如何将记录作为 prop 传递给更新表单(我通过路由打开它,然后我应该传递查询参数等吗?)

You can make a separate Form component that takes props and sets them as initial state, then updates its local state on edit.您可以制作一个单独的 Form 组件,它接受道具并将它们设置为初始 state,然后在编辑时更新其本地 state。 The form also takes a callback on submit.该表单还在提交时进行回调。 Now,现在,

  1. When you want to create a new form you do not pass any data except the create callback当你想创建一个新表单时,除了创建回调之外,你不传递任何数据
  2. when you want to update data, you pass props and the update callback.当你想更新数据时,你传递道具和更新回调。

Here's an example sandbox for reference - https://codesandbox.io/s/happy-thunder-0pjtvr?file=/src/App.js .这是一个供参考的示例沙箱 - https://codesandbox.io/s/happy-thunder-0pjtvr?file=/src/App.js

The form component表单组件

const Form = ({ name = "", email = "", callback }) => {
  const [data, setData] = useState({ name: name, email });
  const handleSubmit = (ev) => {
    ev.preventDefault();
    callback(data);
  };
  useEffect(() => {
    setData({ name, email });
  }, [name, email]);
  return (
    <form onSubmit={handleSubmit}>
      <input
        value={data.name}
        onChange={(ev) => setData({ ...data, name: ev.target.value })}
        name="name"
        placeholder="Name"
      />
      <input
        value={data.email}
        onChange={(ev) => setData({ ...data, email: ev.target.value })}
        name="email"
        placeholder="Email"
      />
      <button>Submit</button>
    </form>
  );
};

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

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