在 React 中创建表单的最佳方法是什么? [英] What is best way to create forms in react?

查看:79
本文介绍了在 React 中创建表单的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 的初学者.我有以下代码:

I am beginner in react. I have following code:

import React, { useState, useEffect } from 'react';
import { Card, Form, Button } from 'react-bootstrap';
import Axios from 'axios'

export function StudentForm({ student, onSuccess, onError, setState }) {
    const url = `http://localhost:9899/api/StudentData`;

    const intialStudent = { Firstname: '', Middlename: '', Lastname: '', DOB: '', Gender: '' };

    const [Student, setStudent] = useState(intialStudent);

    useEffect(() => {
        setStudent(student ? student : intialStudent);
    }, [student]);

    const SaveData = function (studentData) {

        if (student._id) {
            Axios.post(url, { ...studentData }, { headers: { 'accept': 'application/json' } })
                .then(res => {
                    setState(null);
                    onSuccess(res);

                })
                .catch(error => {
                    alert('Error To Edit data');
                });
        }
        else {
            Axios.post(url, studentData, { headers: { 'accept': 'application/json' } })
                .then(res => {
                    setState(null);
                    onSuccess(res);
                })
                .catch(err => onError(err));
        }
    }
    return (
        <Card>
            <Card.Header><h5>{student ? "Edit" : "Add"} Student</h5></Card.Header>
            <Card.Body>
                <Form onSubmit={(e) => { e.preventDefault(); SaveData(Student); }}>
                    <Form.Group><Form.Control type="text" name="Firstname" placeholder="Firstname" value={Student.Firstname} onChange={e => { setStudent({ ...Student, Firstname: e.target.value }) }} /></Form.Group>
                    <Form.Group><Form.Control type="text" name="Middlename" placeholder="Middlename" value={Student.Middlename} onChange={e => setStudent({ ...Student, Middlename: e.target.value })} /></Form.Group>
                    <Form.Group><Form.Control type="text" name="Lastname" placeholder="Lastname" value={Student.Lastname} onChange={e => setStudent({ ...Student, Lastname: e.target.value })} /></Form.Group>
                    <Form.Group><Form.Control type="date" name="DOB" placeholder="DOB" value={Student.DOB} onChange={e => setStudent({ ...Student, DOB: e.target.value })} /></Form.Group>
                    <Form.Group><Form.Control type="text" name="Gender" placeholder="Class" value={Student.Gender} onChange={e => setStudent({ ...Student, Gender: e.target.value })} /></Form.Group>
                    <Button variant="primary" type="submit">Submit</Button>
                </Form>
            </Card.Body>
        </Card>
    );
}

在上面的代码中,我在每个字段的更改事件上设置状态.因此,当我更改任何字段时,它会一次又一次地呈现.如果它是大形式,那么重新呈现可能需要很多时间,所以有没有更好的方法来创建来处理这种情况,或者任何最好的方法在 React 中使用表单的实践?

In above code I am setting state on change event on each field. So it will render again and again when I change any of the field.If it is large form so it may take a lot of time to re-render so is there a better way to create to handle this kind of situation, or any best practices for using forms with react?

推荐答案

对于所有 onChanges,您只能使用一个 Function.看起来像这样;

You can use only one Function for all onChanges. Looks like this;

<Form.Group>
  <Form.Control
     type="text"
     name="Firstname"
     placeholder="Firstname"
     value={Student.Firstname}
     onChange={handleChange} 
  />
</Form.Group>

这是你的handleChange函数;

And this is your handleChange function;

const handleChange = e => {
  const {name, value} = e.target
  setValues({...values, [name]: value})
}

这是你的状态;

const [values, setValues] = useState({
  Firstname: "", 
  Middlename: "", 
  Lastname: "",
  DOB: "",
  Gender: ""
})

我认为这种方式用更少的代码更有效.

I think this way is more effective with less code.

这篇关于在 React 中创建表单的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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