【问题标题】:How to get names and the values from dynamic form. (REACTJS)如何从动态表单中获取名称和值。 (反应)
【发布时间】:2020-07-24 14:06:44
【问题描述】:

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

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

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。 所以可以保存到数据库中。

谢谢。

【问题讨论】:

    标签: javascript reactjs forms jsx mdbreact


    【解决方案1】:

    您所描述的是常规 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} />
    

    【讨论】:

    • 你有什么例子吗?
    • 我不知道怎么做。这些错误:第 158:27 行:'useState' 未定义 no-undef 第 158:36 行:'initialValue' 未定义 no-undef 第 200:14 行:'name' no-restricted-globals 的意外使用
    • 看起来你正在使用 React 类组件,所以我将更新我的答案
    • 我已经更新了我对 React 类组件的回答
    • 对不起,我的水平很低,但我无法得到它,因为我不知道将这段代码放在哪里。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多