简体   繁体   English

在反应中创建 forms 的最佳方法是什么?

[英]What is best way to create forms in 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>
    );
}

In above code I am setting state on change event on each field.在上面的代码中,我在每个字段的更改事件上设置 state。 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?因此,当我更改任何字段时,它会一次又一次地渲染。如果它是大表单,那么重新渲染可能需要很长时间,所以有没有更好的方法来创建来处理这种情况,或者任何最好的使用 forms 与反应的做法?

You can use only one Function for all onChanges.对于所有 onChanges,您只能使用一个 Function。 Looks like this;看起来像这样;

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

And this is your handleChange function;这是你的handleChange function;

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

This is your state;这是你的 state;

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

I think this way is more effective with less code.我认为这种方式用更少的代码更有效。

Managing forms in react is a task complex enough to delegate it to a library.在 react 中管理 forms 是一项复杂到足以将其委托给库的任务。 Alo, big forms are not a good candidate for functional components because the problems that you outlined. Alo,大 forms 不是功能组件的好候选者,因为您概述的问题。 You can, of course, spend the time to tune it up, but I think the effort may not worth the benefit.当然,您可以花时间对其进行调整,但我认为这种努力可能不值得。

My personal recommendation is to try one of the many react form libraries out there.我个人的建议是尝试那里的众多反应表单库之一。 One that I personally like is Formik我个人喜欢的是Formik

If you want to manage the form yourself I recommend to encapsulate the form on stateful component and use the key property for easier reset when you need it.如果您想自己管理表单,我建议将表单封装在有状态组件上,并在需要时使用 key 属性更容易重置。

Another alternative will be the usage of memoization, for example using react.memo.另一种选择是使用 memoization,例如使用 react.memo。 But that will not guarantee success unless your data has the proper shape.但这并不能保证成功,除非您的数据具有适当的形状。 This means, simple values that can be compared between themselves, not arrays, not functions, not objects.这意味着,可以在它们之间进行比较的简单值,而不是 arrays,不是函数,不是对象。

You have to re render the form when an input changed but you don't need to re render every input when you make sure the onChange function doesn't change reference on every render and your input is a pure component (using React.memo for functional component and inherit from React.PureComponent for class components).您必须在输入更改时重新渲染表单,但是当您确保 onChange function 不会更改每次渲染的引用并且您的输入是纯组件时,您不需要重新渲染每个输入(使用 React.memo功能组件并从 React.PureComponent 继承 class 组件)。

Here is an example of optimized inputs.这是优化输入的示例。

 const { useEffect, useCallback, useState, memo, useRef, } = React; function App() { return <StudentForm />; } //put initial student here so it doesn't change reference and quits the linter // in useEffect const initialStudent = { Firstname: '', Middlename: '', }; function StudentForm({ student }) { const [Student, setStudent] = useState(initialStudent); //useCallback so onChange is not re created and causes re rendering // of components that didn't change const onChange = useCallback( (key, value) => setStudent(student => ({...student, [key]: value })), [] ); useEffect(() => { setStudent(student? student: initialStudent); }, [student]); const SaveData = function(studentData) { console.log('saving data:', studentData); }; return ( <form onSubmit={e => { e.preventDefault(); SaveData(Student); }} > <InputContainer type="text" name="Firstname" placeholder="Firstname" value={Student.Firstname} stateKey="Firstname" //provide state key onChange={onChange} /> <InputContainer type="text" name="Middlename" placeholder="Middlename" value={Student.Middlename} stateKey="Middlename" onChange={onChange} /> <button type="submit">Submit</button> </form> ); } //make this a pure component (does not re render if nothing changed) const InputContainer = memo(function InputContainer({ type, name, placeholder, value, onChange, stateKey, }) { const rendered = useRef(0); rendered.current++; return ( <div> <div>{rendered.current} times rendered.</div> <input type={type} name={name} value={value} placeholder={placeholder} onChange={e => //pass state key and new value to onChange onChange(stateKey, e.target.value) } /> </div> ); }); ReactDOM.render(<App />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

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

相关问题 在React中创建组件参数的最佳方法是什么? - What is the best way to create parameter of the component in React? 为 React JS Ajax 调用创建 Loading Animation 的最佳方法是什么? - What is the best way to create a Loading Animation for React JS Ajax calls? 为 React 和 Preact 创建组件库的最佳方法是什么? - What is the best way to create component library for both React and Preact? 许多切换表单的最佳方式是什么 - What is the best way for a lot of toggle forms 以本机形式处理键盘的最佳方法是什么? 矿井一直躲藏/显示并分散注意力 - What is the best way to handle the keyboard in react native forms? Mine keeps hiding / showing and is distracting 在 onClick 触发器之后创建反应组件的最佳方法是什么(好的做法?)? - What's the best way (good practice !) to create a react component after an onClick trigger? 在React中创建向导组件的最佳方法 - Best way to create a Wizard component in React 使用 React 功能组件抽象 forms 和输入的最佳方法? - best way to abstract forms and inputs using React functional components? 编写此 React 代码的最佳方法是什么? - What is the best way to write this React code? 为 React 构建配置文件的最佳方法是什么? - What is the best way to structure a configuration file for React?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM