如何使用React Js合并表单? [附摘要] [英] How to combine form using React Js? [Snippet Attached]

查看:50
本文介绍了如何使用React Js合并表单? [附摘要]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Reactjs中像这样 https://jsonresume.org/schema/(JSON格式).

index.js:

import React, { useState, Fragment } from 'react';
import BasicDetails from '../components/basic_details';
import EmploymentDetails from '../components/employment_details';

const App = () => {
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('get the whole form json here');
  };

  return (
    <>
      <h1>Dynamic Form Fields in React</h1>
      <form onSubmit={handleSubmit}>
        Basic Details:
        <br />
        <hr />
        <BasicDetails />
        <br />
        <br />
        Employment Details:
        <br />
        <hr />
        <EmploymentDetails />
        <div className="submit-button">
          <button
            className="btn btn-primary mr-2"
            type="submit"
            onSubmit={handleSubmit}
          >
            Save
          </button>
        </div>
        {/* <pre>{JSON.stringify(inputFields, null, 2)}</pre> */}
      </form>
    </>
  );
};

export default App;

<BasicDetails /><EmploymentDetails />代码的组件可在随附的代码和框中找到.

在这里,我将表单制作为每个相似的组件都有一个单独的组件,

---> Basic Details
---> Employment Details
---> ...So on ...

要求:

我需要将这些输入以单个json格式组合 像这样

现在我有不同文件中的基本详细信息和工作详细信息,那么如何将这两个文件/组件组合在一起以形成一个完整的JSON?

单击提交"按钮(index.js)时预期的JSON格式:

{
  "basicDetails": {
    "firstName": "John",
    "lastName": "Doe"
  },
  "companyDetails": [{
     "companyName": "xyz",
     "designation": "lmn"
   },
   {
     "companyName": "abc",
     "designation": "def"
   }
 ]
}

查看以下具有相应组件中输入字段JSON格式的codeandbox. 我需要将它们结合起来,并在单击提交"按钮时显示最终表格.

代码和框: https ://codesandbox.io/s/next-dynamic-testing-issue-forked-ieqf5

注意:组件部分将继续增加,就像我们将添加新组件一样,例如技能,教育细节(此处未添加,将来还会添加)等.因此,请相应地提供解决方案

非常感谢.

解决方案

可以使用 API.想法是让您的状态在多个组件之间共享.

下面的代码将包含一个formValue,可以在EmploymentDetailsBasicDetails组件上进行访问.

 // components/form_context.js

import React, { useState } from 'react';

export const FormContext = React.createContext();

export function FormProvider({ children }) {
  const [formValue, setFormValue] = useState({
    basicDetails: {
      firstName: '',
      lastName: '',
    },
    companyDetails: [
      {
        companyName: '',
        designation: '',
      },
    ],
  });

  return (
    <FormContext.Provider value={[formValue, setFormValue]}>
      {children}
    </FormContext.Provider>
  );
}
 

在您的BasicDetails上,您通过

访问上面的formValue状态

 // components/basic_details.js

import { FormContext } from './form_context';

const BasicDetails = () => {
  const [value, setValue] = React.useContext(FormContext); // here
  const { basicDetails } = value;

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setValue((prev) => {
      const basicDetails = { ...prev.basicDetails, [name]: value };
      return { ...prev, basicDetails };
    });
  };

  ...
};
 

-还请注意我们是如何实现handleInputChange的,我们正在使用来自FormContextsetValue更新formValue.

检查演示,然后问我是否要澄清任何内容.在此处中阅读.

I am trying to make a form in reactjs like this https://jsonresume.org/schema/ (JSON Format).

index.js:

import React, { useState, Fragment } from 'react';
import BasicDetails from '../components/basic_details';
import EmploymentDetails from '../components/employment_details';

const App = () => {
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('get the whole form json here');
  };

  return (
    <>
      <h1>Dynamic Form Fields in React</h1>
      <form onSubmit={handleSubmit}>
        Basic Details:
        <br />
        <hr />
        <BasicDetails />
        <br />
        <br />
        Employment Details:
        <br />
        <hr />
        <EmploymentDetails />
        <div className="submit-button">
          <button
            className="btn btn-primary mr-2"
            type="submit"
            onSubmit={handleSubmit}
          >
            Save
          </button>
        </div>
        {/* <pre>{JSON.stringify(inputFields, null, 2)}</pre> */}
      </form>
    </>
  );
};

export default App;

Compenents such as <BasicDetails /> and <EmploymentDetails /> code can be found in attached codesandbox.

Here I have made the form to have a separate components for each like,

---> Basic Details
---> Employment Details
---> ...So on ...

Requirement:

I am in the need to combine these inputs in a single json format like this

For now I have basic details and employment details which is in different files So how can I combine these two files/components to form a complete JSON?

Expected JSON format on click of the submit button (index.js):

{
  "basicDetails": {
    "firstName": "John",
    "lastName": "Doe"
  },
  "companyDetails": [{
     "companyName": "xyz",
     "designation": "lmn"
   },
   {
     "companyName": "abc",
     "designation": "def"
   }
 ]
}

Look at the below codesandbox that has the JSON format of input fields in respective component. I am in the need to combine those and display final form on click of submit button.

Codesandbox: https://codesandbox.io/s/next-dynamic-testing-issue-forked-ieqf5

Note: The component sections will keep on increasing like we will add new components like skills, education details (not added here but will add in future) etc.., so kindly provide the solution accordingly.

A big thanks in advance..

解决方案

This can be done using Context API. The idea is to have your state shared across multiple components.

The code below will hold a formValue that will be accessed on EmploymentDetails and BasicDetails components.

// components/form_context.js

import React, { useState } from 'react';

export const FormContext = React.createContext();

export function FormProvider({ children }) {
  const [formValue, setFormValue] = useState({
    basicDetails: {
      firstName: '',
      lastName: '',
    },
    companyDetails: [
      {
        companyName: '',
        designation: '',
      },
    ],
  });

  return (
    <FormContext.Provider value={[formValue, setFormValue]}>
      {children}
    </FormContext.Provider>
  );
}

On your BasicDetails, you access the formValue state above through

// components/basic_details.js

import { FormContext } from './form_context';

const BasicDetails = () => {
  const [value, setValue] = React.useContext(FormContext); // here
  const { basicDetails } = value;

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setValue((prev) => {
      const basicDetails = { ...prev.basicDetails, [name]: value };
      return { ...prev, basicDetails };
    });
  };

  ...
};

- also notice how we implement our handleInputChange, we're updating the formValue using setValue coming from our FormContext.

Check the demo, and ask me if you want to clarify anything. Read Context docs here.

这篇关于如何使用React Js合并表单? [附摘要]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆