简体   繁体   English

如何使用 React Hooks 在提交到表格时添加表单值

[英]How to add form values on submit to a table using React Hooks

I'm building a project management app, and I'm a bit new to Hooks, so please bear with me.我正在构建一个项目管理应用程序,我对 Hooks 有点陌生,所以请耐心等待。

Link to the app , link to the code .链接到应用程序,链接到代码

The user should have the ability to add a new project.用户应该能够添加新项目。 They can add a name, description and date, which would then be automatically added to the table.他们可以添加名称、描述和日期,然后这些信息会自动添加到表格中。

Currently, I'm unable to get it working.目前,我无法让它工作。 A user is unable to add a new project.用户无法添加新项目。

I can type in a new date in the Date field - but anytime I try to type in the Name or Description field, the values don't show and I get console errors thrown:我可以在“日期”字段中输入新日期 - 但每当我尝试在“名称”或“描述”字段中输入时,这些值都不会显示,并且会引发控制台错误:

"Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method isDefaultPrevented on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist()." “警告:出于性能原因重用此合成事件。如果您看到这一点,您正在访问方法isDefaultPrevented在已发布/无效的合成事件上。这是一个无操作功能。如果您必须保留原始合成事件周围,​​使用 event.persist()。”

The main issues that I'm trying to fix:我试图解决的主要问题:

  • Allow the user to type in the fields允许用户在字段中输入
  • On hitting submit, they go into their proper areas in the table点击提交后,他们进入表格中的适当区域

In my code, mainCrud.js houses the initial data as well as the Add Project functionality.在我的代码中,mainCrud.js 包含初始数据以及添加项目功能。 The data's passed down into the actual CrudAdd component, which houses the "Add Project" form:数据向下传递到实际的 CrudAdd 组件中,该组件包含“添加项目”表单:

import React, { useState } from "react";

import CrudIntro from "../crud/crudIntro/crudIntro";
import CrudAdd from "../crud/crudAdd/crudAdd";
import CrudTable from "../crud/crudTable/crudTable";

const MainCrud = props => {
  // Project Data
  const projectData = [
    {
      id: 1,
      name: "Skid Steer Loaders",
      description:
        "To advertise the skid steer loaders at 0% financing for 60 months.",
      date: "February 1, 2022"
    },
    {
      id: 2,
      name: "Work Gloves",
      description: "To advertise the work gloves at $15.",
      date: "February 15, 2022"
    },
    {
      id: 3,
      name: "Telehandlers",
      description: "To advertise telehandlers at 0% financing for 24 months.",
      date: "March 15, 2022"
    }
  ];

  const [projects, setProject] = useState(projectData);

  // Add Project
  const addProject = project => {
    project.id = projectData.length + 1;
    setProject([...projects, project]);
  };

  return (
    <div>
      <section id="add">
        <CrudIntro title={props.title} subTitle={props.subTitle} />
        <CrudAdd addProject={addProject} />
      </section>
      <section id="main">
        <CrudTable projectData={projects} />
      </section>
    </div>
  );
};

export default MainCrud;

In CrudAdd.js, I'm setting the initial state of the form, updating the state of the form and adding the form submit:在 CrudAdd.js 中,我正在设置表单的初始状态,更新表单的状态并添加表单提交:

import React, { useState } from "react";

import "../crudAdd/crud-add.scss";
import "../../button.scss";

const CrudAdd = props => {
  // Set the initial state of the form
  const initialFormState = {
    id: null,
    name: "",
    description: "",
    date: ""
  };
  const [project, setProject] = useState(initialFormState);

  // Update state within the form
  const handleInputChange = e => {
    const { name, value } = e.target;
    setProject({ ...project, [name]: value });

    console.log(e);
  };

  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault();
          if (!project.name || !project.username) return;

          props.addProject(project);
          setProject(initialFormState);
        }}
      >
        <input
          type="name"
          placeholder="Name..."
          id="name"
          value={project.name}
          onChange={handleInputChange}
        />
        <input
          type="description"
          placeholder="Description..."
          id="description"
          value=""
        />
        <input type="name" placeholder="Date..." id="date" />
      </form>
      <button className="btn btn-primary">Add Project</button>
    </div>
  );
};

export default CrudAdd;

Any idea?任何的想法? Thanks in advance.提前致谢。

I got what's the problem in your code.我知道你的代码有什么问题。 You have not add name property in your input fields您尚未在输入字段中添加name属性

 <input name="name" type="name" placeholder="Name..." id="name" value={project.name} onChange={handleInputChange} /> <input name="description" type="description" placeholder="Description..." id="description" value={project.description} />

React:如何提交表单<textarea>&lt;i&gt;with enter key and without a submit button with React Hooks?&lt;/div&gt;&lt;/i&gt;&lt;b&gt;带有回车键且没有带有 React Hooks 的提交按钮?&lt;/div&gt;&lt;/b&gt;</textarea><div id="text_translate"><p> Halo 伙计们,我对反应很陌生,我想提交一个只有文本区域的表单,并按下enter键。 我遵循了一些 SO 问题,但仍然没有运气,因为它没有被提交。 我还想在提交后清除文本区域。 我怎样才能用下面的代码做到这一点?</p><p> 这是我目前拥有的代码。</p><pre> const { register, handleSubmit, control, errors } = useForm(); const CommentOnSubmit = (data) =&gt; { let formData = new FormData(); formData.append('content', data.content); formData.append('user', user?.id); axiosInstance.post(`api/blogs/` + slug + `/comment/`, formData); }; // const commentEnterSubmit = (e) =&gt; { // if(e.key === 'Enter' &amp;&amp; e.shiftKey == false) { // return( // e.preventDefault(), // CommentOnSubmit() // ) // } // } &lt;form noValidate onSubmit={handleSubmit(CommentOnSubmit)}&gt; &lt;div className="post_comment_input"&gt; &lt;textarea type="text" placeholder="Write a comment..." name="content" ref={register({required: true, maxLength: 1000})} /&gt; &lt;/div&gt; &lt;div className="comment_post_button"&gt; &lt;Button type="submit" variant="contained" color="primary"&gt;comment&lt;/Button&gt; &lt;/div&gt; &lt;/form&gt;</pre><p> 请帮忙。</p><p> 非常感谢。</p></div> - React: How to submit a form with <textarea> with enter key and without a submit button with React Hooks?

暂无
暂无

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

相关问题 React Hooks 表单:提交时未定义的值 - React Hooks Form : undefined values on submit 使用纯 React.js Hooks 提交表单后如何重置我的输入字段,没有库 - How to reset my input field after I submit form using pure React.js Hooks, no libraries 如何使用反应钩子验证表单? - How to validate form using react hooks? React:如何提交表单<textarea>&lt;i&gt;with enter key and without a submit button with React Hooks?&lt;/div&gt;&lt;/i&gt;&lt;b&gt;带有回车键且没有带有 React Hooks 的提交按钮?&lt;/div&gt;&lt;/b&gt;</textarea><div id="text_translate"><p> Halo 伙计们,我对反应很陌生,我想提交一个只有文本区域的表单,并按下enter键。 我遵循了一些 SO 问题,但仍然没有运气,因为它没有被提交。 我还想在提交后清除文本区域。 我怎样才能用下面的代码做到这一点?</p><p> 这是我目前拥有的代码。</p><pre> const { register, handleSubmit, control, errors } = useForm(); const CommentOnSubmit = (data) =&gt; { let formData = new FormData(); formData.append('content', data.content); formData.append('user', user?.id); axiosInstance.post(`api/blogs/` + slug + `/comment/`, formData); }; // const commentEnterSubmit = (e) =&gt; { // if(e.key === 'Enter' &amp;&amp; e.shiftKey == false) { // return( // e.preventDefault(), // CommentOnSubmit() // ) // } // } &lt;form noValidate onSubmit={handleSubmit(CommentOnSubmit)}&gt; &lt;div className="post_comment_input"&gt; &lt;textarea type="text" placeholder="Write a comment..." name="content" ref={register({required: true, maxLength: 1000})} /&gt; &lt;/div&gt; &lt;div className="comment_post_button"&gt; &lt;Button type="submit" variant="contained" color="primary"&gt;comment&lt;/Button&gt; &lt;/div&gt; &lt;/form&gt;</pre><p> 请帮忙。</p><p> 非常感谢。</p></div> - React: How to submit a form with <textarea> with enter key and without a submit button with React Hooks? React Hooks Form:提交时未定义的值 - React Hooks Form: undefined value on submit React Hooks 仅在表单提交时更新状态 - React Hooks only update state on form submit 如何使用 React.js 从不同页面的表单中添加表中的输入值? - How to add input values in table from a form in different page using React.js? 如何在表单中添加两个“ on Submit =”值? - How to add two “on submit=” values to a form? 如何使用反应钩子 useState 从 API 向对象添加属性 - How to add property to an object from an API using react hooks useState 如何使用钩子将数组添加到 React 中的空数组 - How to add an array to an empty array in React using hooks
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM