如何在提交函数的reactjs中将表单值作为FormData传递
Posted
技术标签:
【中文标题】如何在提交函数的reactjs中将表单值作为FormData传递【英文标题】:How to pass form values as FormData in reactjs on submit function 【发布时间】:2017-08-22 11:36:34 【问题描述】:我有一个使用 json 数据生成的动态表单,我需要在提交时传递表单输入值。我打算将值作为表单数据发送。我已经创建了提交函数,但我不知道如何在 formdata 中附加值,并且需要使用 Axios 通过 post 方法。我是新手,谁能告诉我该怎么做。下面是我的代码。
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'));
【问题讨论】:
【参考方案1】:要使用axios
发布FormData
,您需要在header
中指定您要发送FormData
,因为content-type
应该是multipart/form-data
。
检查一下,如何使用FormData
和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);
);
【讨论】:
感谢您的帮助。我已经用你更新的代码编辑了这个问题。我想将输入值作为第二个参数传递给 formdata,以便我可以在 formdata 中看到标签和相应的值。我试过了,但我无法解决它。【参考方案2】:您可以像这样访问 FormData:
handleSubmit(event)
// Prevent default behavior
event.preventDefault();
const data = new FormData(event.target);
// Access FormData fields with `data.get(fieldName)`
// For example, converting to upper case
data.set('username', data.get('username').toUpperCase());
// Do your Axios stuff here
这是表单的代码:
render()
return (
<form onSubmit=this.handleSubmit>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<button>Send data!</button>
</form>
);
【讨论】:
【参考方案3】:您可以动态更新对状态的更改。见例子Here
constructor(props)
super(props);
this.state = value: '';
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
将您的所有字段绑定到您的状态。示例
this.sate = name: '', username: '', select: ''
然后
_renderElement: function(group)
switch(group.Type)
case 'text':
return <input className=group.cssClassName
id=group.Label
placeholder=group.Placeholder
value=this.state[group.name]
onChange=this.handleUsernameChange
required=group.Mandatory == 'Y'? true: false/>
case 'dropdown':
return <select className=group.cssClassName>
onChange=this.handleDropDropDownChange
<option value="">group.Placeholder </option>
group.Values.map(el => <option>el.Value</option>)
</select>
</div>
注意 group.name 可以是用户名、名称或您为控件命名的任何名称。
handleUsernameChange(event)
this.setState(username: event.target.value);
handleDropDownChange(event)
this.setState(select: event.target.value);
然后在发帖时
axios.post(url, this.state, 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 onSubmit=this.handleSubmit>
<div className="form-group">
<div className="col-xs-5">
this.renderForm()
<input type="submit" value="Submit" />
</div>
</div>
</form>
</div>
</div>
</div>
)
);
在这里查看文档https://facebook.github.io/react/docs/forms.html
【讨论】:
【参考方案4】:使用获取
function uploadFile(file)
fetch('https://path/to/api',
// content-type header should not be specified!
method: 'POST',
body: file,
)
.then(response => response.json())
.then(success =>
// Do something with the successful response
)
.catch(error => console.log(error)
);
【讨论】:
它在 response.json() 处给出语法错误。在用大括号括起来语句 response.json() 后它得到修复,即 response.json()以上是关于如何在提交函数的reactjs中将表单值作为FormData传递的主要内容,如果未能解决你的问题,请参考以下文章