如何从动态表单中获取名称和值。 (REACTJS)

How to get names and the values from dynamic form. (REACTJS)

我在渲染中以这种形式动态渲染, 如何在点击提交时获取名称和值?

这是部分 os 这里的代码形式是从数组生成的。

import React, { Component, Fragment } from 'react';
import { MDBContainer, MDBBtn, MDBModal, MDBModalBody, MDBModalHeader, MDBModalFooter, MDBIcon} from 'mdbreact';
import { Form, Input, DatePicker, Button } from "antd";
import { connect } from "react-redux";
import axios from "axios";
import moment from "moment";
//import { createHashHistory } from 'history';
import TimeStamp from "./TimeStamp"; //DEBUG.

const FormItem = Form.Item;



class ModalPage extends Component {

constructor(props) {


    super(props);
};




state = {
    modal: false
};



toggle = () => {
    this.setState({
    modal: !this.state.modal
    });
}

handleFormSubmit = async (event, requestType, itemID) => {
    event.preventDefault();
    console.log("@@@@@@@@-----event---->", event)
    console.log("@@@@@@@@-----requestType---->", requestType)
    console.log("@@@@@@@@-----itemID---->", itemID)


    // Se define en Orígen en DynForm.
    const postObj = {
    fecha_alta: event.target.elements.fecha_alta.value,
    nombre: event.target.elements.nombre.value,
    usuario_id: event.target.elements.usuario_id.value
    }

    axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
    axios.defaults.xsrfCookieName = "csrftoken";
    axios.defaults.headers = {
    "Content-Type": "application/json",
    Authorization: `Token ${this.props.token}`,

    };

    // Transpaso de variables recibidas:
    let ApiPath =  this.props.data[0].ApiEndPointPath;





    if (requestType === "post") {
    await axios.post(`http://192.168.196.49:8000/${ApiPath}/api/create/`, postObj)
        .then(res => {
        if (res.status === 201) {
            this.setState({modal: false});
            //this.props.history.push(`/proyectos/clientes/`);
            window.location.reload(true);


        }
        })
    } else if (requestType === "put") {
    await axios.put(`http://192.168.196.49:8000/${ApiPath}/api/${itemID}/update/`, postObj)
        .then(res => {
        if (res.status === 200) {
            this.setState({modal: false});
            //this.props.history.push(`/proyectos/clientes/`);
            window.location.reload(false);
        }
        })
    }
};

deleteDato(recibe){
    //<ModalBorrar />
    //event.preventDefault();
    //const articleID = this.props.match.params.articleID;
    console.log("##_deleteDato## el valor es: ", recibe );
    axios.defaults.headers = {
    "Content-Type": "application/json",
    Authorization: `Token ${this.props.token}`
    };
    let ApiPath =  this.props.data[0].ApiEndPointPath;

    axios.delete(`http://192.168.196.49:8000/${ApiPath}/api/${recibe}/delete/`)
    .then(res => {
    if (res.status === 204) {
        console.log("Dato Borrado!!!");
        this.setState({modal: false});
        window.location.reload(false);


    }
    })
};





//DEBUG:
render() {

    let DynForm = this.props.DynForm;




    const debug = {
    Mensage: "Campo personalizado para una nota específica.",
    Fichero: "Modal.js",

    };


    TimeStamp(debug, this.props);






    const renderHerramientaButton = ()=>{
    if( this.props.TipoBoton === "editar"){ //------------ --Editar --------------

        return <MDBIcon className="light-blue-text" icon="edit" size="1x" onClick={this.toggle}/>
    } else if( this.props.TipoBoton === "nuevo"){ //---------Nuevo --------------

        return <MDBBtn size="sm" color="light-blue" onClick={this.toggle}>Nuevo</MDBBtn>

    } else if( this.props.TipoBoton === "borrar"){ //------- Borar --------------

        return <MDBIcon className="red-text" icon="trash-alt" size="1x" onClick={this.toggle}/>

    } else { 

        return <MDBIcon className="red-text" icon="flushed" size="1x" onClick={this.toggle} />
    }
    }





    const NuevosDatos = ()=>{
        return (
        <MDBContainer>
        {/* BUTTON que se renderisa en la página anterior.*/} 
        {renderHerramientaButton()} 

        {/* MODAL */}
        <MDBModal isOpen={this.state.modal} toggle={this.toggle}  backdrop={false}   >
        <MDBModalHeader  toggle={this.toggle}>
            <p className="text-uppercase">{this.props.data[0].ModalTitleNuevo}</p>
        </MDBModalHeader>
        <MDBModalBody>

            <Form
            onSubmit={event =>
            this.handleFormSubmit(
                event,
                this.props.requestType,
                this.props.itemID
            )
            }
            >

            {/* Usando Tenary operation */}
            <div>
            {DynForm.map((value) => (
                <Fragment>
                <FormItem label={value.label}>

                {value.tipo === "input" ? 
                <Input name={value.nombre} placeholder={value.placeholder} defaultValue={value.defaultValue}/> : 
                <DatePicker name={value.nombre} defaultValue={moment(value.defaultValue)}/>}




                </FormItem>

                </Fragment> 

            ))}
            </div>



            <FormItem>
            <Button type="primary" htmlType="submit" color="#389e0d">
                {this.props.btnText}
            </Button>
            </FormItem>
            </Form>
        </MDBModalBody>
        </MDBModal>
        </MDBContainer>
        );
    };


    const EditarDatos = ()=>{
    return (
    <MDBContainer>
    {/* BUTTON que se renderisa en la página anterior.*/} 
    {renderHerramientaButton()} 

    {/* MODAL */}
    <MDBModal isOpen={this.state.modal} toggle={this.toggle}  backdrop={false}   >
    <MDBModalHeader toggle={this.toggle}>
        {this.props.data[0].ModalTitleEditar}
    </MDBModalHeader>
    <MDBModalBody>

        <Form
        onSubmit={event =>
            this.handleFormSubmit(
            event,
            this.props.requestType,
            this.props.itemID
        )
        }
        >

        {/* Usando Tenary operation */}
        <div>
            {DynForm.map((value) => (
                <Fragment>
                <FormItem label={value.label}>

                {value.tipo === "input" ? 
                <Input name={value.nombre} placeholder={value.placeholder} defaultValue={value.defaultValue}/> : 
                <DatePicker name={value.nombre} defaultValue={moment(value.defaultValue)}/>}

                </FormItem>

                </Fragment> 

            ))}
            </div>

        <FormItem>
        <Button type="primary" htmlType="submit" color="#389e0d">
            {this.props.btnText}
        </Button>
        </FormItem>
        </Form>
    </MDBModalBody>
    </MDBModal>
    </MDBContainer>
    );
};



    const BorradoDatos = ()=>{
    return (
    <MDBContainer>
    {/* BUTTON que se renderisa en la página anterior.*/} 
    {renderHerramientaButton()} 

    {/* MODAL */}
    <MDBModal isOpen={this.state.modal} toggle={this.toggle}  backdrop={false}   >
    <MDBModalHeader toggle={this.toggle}>
        {this.props.data[0].ModalTitleBorrar}
    </MDBModalHeader>
    <MDBModalBody>

    <p className="text-md-left">{this.props.campos[0].label}{": "}{this.props.formdataNombre}
        <br></br>
        {this.props.campos[2].label}{": "}{this.props.formdata_Usuario_id}
        <br></br>
        {this.props.campos[1].label}{": "}{this.props.formdataFecha_alta}
        </p>


    </MDBModalBody>
    <MDBModalFooter>                            
        <MDBBtn outline color="danger" size="sm" onClick={() => this.deleteDato(this.props.itemID)}>{this.props.btnText}</MDBBtn>
        <MDBBtn outline color="success" size="sm" onClick={this.toggle}>{this.props.btnText2}</MDBBtn>
        </MDBModalFooter>
    </MDBModal>
    </MDBContainer>
    );
};





    if ( this.props.TipoBoton === "editar") {

    return  (
        <EditarDatos />

        );
    } else if ( this.props.TipoBoton === "borrar") {

    return  (
        <BorradoDatos />

        );
    } else {
    return  (
        <NuevosDatos />

        );

    }









}
}

const mapStateToProps = state => {
    return {
    token: state.token
    };
};

export default connect(mapStateToProps)(ModalPage);

使用的表格来自mdbreact。 表格已正确生成。 我只需要获取每个 from 中引入的数据值来准备我的 postobject。 这样就可以保存到数据库中了。

谢谢。

您所描述的是常规 HTML,其中每个输入元素都在其 DOM 节点中维护其值。但这不是它与 React 一起工作的方式。使用 React,您必须通过向每个输入元素添加 onChange 属性 来自己管理所有输入元素的状态。因此,当用户单击提交按钮时,您已经拥有组件状态中的所有值。

例如:

// Create the value state
state = { value: "" };

// Handle the input change
onChange = (event) => {
  this.setState(value: event.target.value);
}

// Render the Input element
<Input name='test' value={this.state.value} onChange={this.onChange} />