如何在提交函数的reactjs中将表单值作为FormData传递 [英] How to pass form values as FormData in reactjs on submit function

查看:32
本文介绍了如何在提交函数的reactjs中将表单值作为FormData传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 json 数据生成的动态表单,我需要在提交时传递表单输入值.我打算将值作为 formdata 发送.我已经创建了提交函数,但我不知道如何在 formdata 中附加值,需要使用 Axios 传递 post 方法.我是新来的反应谁能告诉我如何做到这一点.下面是我的代码.

var DATA = {索引列表":[{标签":名称",类型":文本",正则表达式":",默认值":",值":{钥匙":",价值":"},验证消息":",脚本":",强制性":Y",最大长度":16",minLength":7",格式":字母数字",cssClassName":表单控件",占位符":"},{标签":选择语言",类型":下拉",正则表达式":",Default_Val":英语",值":[{键":选项1",价值":英语";},{键":选项2",价值":西班牙语"}],验证消息":",脚本":",强制性":Y",最大长度":",minLength":",格式":",cssClassName":表单控件",占位符":"},{标签":类型",类型":无线电",正则表达式":",默认值":",值":[{键":选项1",值":Form1"}, {键":选项2",值":Form2"}, {键":选项3",值":Form3"},{键":选项4",值":Form4"},{键":选项5",值":Form5"}],验证消息":",脚本":",强制性":Y",最大长度":",minLength":",格式":",cssClassName":表单控件",占位符":"}]};var Menu = React.createClass({getInitialState() {返回 {}},_renderElement:功能(组){开关(组.类型){案例文本":返回 (<输入className={group.cssClassName}id={group.Label}占位符={group.Placeholder}required={group.Mandatory == 'Y' ?真假}/>);案例下拉":返回 (<select className={group.cssClassName}><option value="">{group.Placeholder}</option>{group.Values.map(el => <option>{el.Value}</option>)}</选择>);案例收音机":返回 (

<div for="let value of group.Values">{group.Values.map(el=>(<label><input name="radios"/>{el.Value}</label>))}

);}},渲染形式:函数(){var 数据 = DATA.indexList;返回 data.map(group => {返回 (<div><label for={group.Label}>{group.Label}</label><div>{this._renderElement(group)}

)});},_onSubmit: 函数 () {让 formData = new FormData();var data1 = DATA.indexList;data1.map(组=> {formData.append(group.Label);//如何获取这里的输入值作为第二个参数,以便我可以将标签名称和对应的值传递给表单数据.});常量配置 = {标题:{'内容类型':'多部分/表单数据'}}axios.post('',formData, config).then(响应 => {控制台日志(响应);}).catch(错误=> {控制台日志(错误);});},渲染:函数(){返回 (<div className="容器"><br/><div className="panel panel-primary"><div className="panel-heading">表单</div><div className="panel-body"><表格><div className="form-group"><div className="col-xs-5">{this.renderForm()}<按钮类型=提交"className =btn btn-primary";onSubmit={this._onSubmit()}>提交

</表单>

)}});ReactDOM.render(

, document.getElementById('app'));

解决方案

使用axios发布FormData,需要在header中指定您正在发送 FormData,因为 content-type 应该是 multipart/form-data.

检查一下,如何将FormDataaxios一起使用:

let formData = new FormData();//表单数据对象formData.append('name', 'ABC');//附加键值对的值formData.append('age', 20);常量配置 = {标题:{'内容类型':'多部分/表单数据'}}axios.post(url, formData, config).then(响应 => {控制台日志(响应);}).catch(错误=> {控制台日志(错误);});

I have a dynamic form generated using json data and I need to pass the form input values on submit. I'm planning to send the values as formdata. I have created submit function but i don't know how to append the values in formdata and need to pass through post method using Axios. I'm new to react can anyone tell me how to do this. Below is my code.

var DATA = {
  "indexList": [{
    "Label": "Name",
    "Type": "text",
    "Regex": "",
    "Default_Val": "",
    "Values": {
      "Key": "",
      "Value": ""
    },
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"16",
    "minLength":"7",
    "format":"Alphanumeric",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Select Language",
    "Type": "dropdown",
    "Regex": "",
    "Default_Val": "English",
    "Values": [{
      "Key": "option1",
      "Value": "English"
    },{
      "Key": "option2",
      "Value": "Spanish"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Type",
    "Type": "radio",
    "Regex": "",
    "Default_Val": "",
    "Values": [{
      "Key": "option1",
      "Value": "Form1"
    }, {
      "Key": "option2",
      "Value": "Form2"
    }, {
      "Key": "option3",
      "Value": "Form3"
    },{
      "Key": "option4",
      "Value": "Form4"
    },{
      "Key": "option5",
      "Value": "Form5"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  }
  ]
};

var Menu = React.createClass({

  getInitialState() {
    return {
    }
  },

  _renderElement: function(group){
    switch(group.Type){
      case 'text':
        return (
          <input
            className={group.cssClassName}
            id={group.Label}
            placeholder={group.Placeholder}
            required={group.Mandatory == 'Y' ? true : false}
          />
        );

      case 'dropdown':
        return (
          <select className={group.cssClassName}>
            <option value="">{group.Placeholder}</option>
            {group.Values.map(el => <option>{el.Value}</option>)}
          </select>
        );

      case 'radio':
        return (
          <div className={group.Type}>
            <div for="let value of group.Values">
              {group.Values.map(el=> (
                <label><input name="radios"/>{el.Value}</label>
              ))}
            </div>
          </div>
        );
    }
  },

  renderForm: function () {
    var data = DATA.indexList;
    return data.map(group => {
      return (
        <div>
          <label for={group.Label}>{group.Label}</label>
          <div>
            {this._renderElement(group)}
          </div>
        </div>
      )
    });
  },


  _onSubmit: function () {
    let formData = new FormData();
    var data1 = DATA.indexList;
    data1.map(group => {
      formData.append(group.Label); // How to get the input value here as a second parameter, so than i can pass the label name and corresponding value to form data.
    });

    const config = {
      headers: { 'content-type': 'multipart/form-data' }
    }

    Axios.post('',formData, config)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
  },

  render: function() {
    return (    
      <div className="container">
        <br/>
        <div className="panel panel-primary">
          <div className="panel-heading">Form</div>
          <div className="panel-body">
            <form>
              <div className="form-group">
                <div className="col-xs-5">
                  {this.renderForm()}
                  <button type="submit" className="btn btn-primary" onSubmit={this._onSubmit()}>Submit</button>
                </div>
              </div>
            </form>
          </div>      
        </div>
      </div>
    )
  }
});

ReactDOM.render(<Menu/>, document.getElementById('app'));

解决方案

To post the FormData using axios, you need specify in header that you are sending FormData, for that content-type should be multipart/form-data.

Check this, how to use FormData with axios:

let formData = new FormData();    //formdata object

formData.append('name', 'ABC');   //append the values with key, value pair
formData.append('age', 20);

const config = {     
    headers: { 'content-type': 'multipart/form-data' }
}

axios.post(url, formData, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });

这篇关于如何在提交函数的reactjs中将表单值作为FormData传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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