我有一个带有表单的模态,表单字段用于动态呈现。我需要收集用户输入的所有字段并将其发送到后端。这是我的组件代码,用于呈现动态表单字段:
import React from 'react'
import { Link } from 'react-router-dom'
import { Button, Form, Input } from 'semantic-ui-react'
const FormItem = Form.Input;
var urlPrefix = "http://localhost:8000/"
class CreateForm extends React.Component {
state = {
columns : [],
formLayout: 'vertical',
}
handleOk = (e) => {
//PLEASE HELP ME HERE
e.preventDefault();
this.collection.add(this.state);
}
componentWillMount() {
fetch(urlPrefix + 'api/modules/3', {
method: "GET",
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
"Content-Type": "application/json"
}
}).then(response => response.json().then(data => ({
data: data, status: response.status}),))
.then(a => {
var field, fields = []
a.data.module_fields.forEach((element) =>{
field = {
placeholder: element.text,
label: element.name,
key: element.id,
default_value : element.default_value,
required : element.required
}
fields.push(field)
});
const children = [];
fields.forEach(function(element){
children.push(
<FormItem
label={element.label}
key={element.key}
id={element.label}
placeholder={element.placeholder}
/>
);
})
this.setState({fields: children})
})
}
render() {
return (
<div>
<Form
className="ant-advanced-search-form"
>
{this.state.fields}
<Button key="back" onClick={this.handleCancel}>Close</Button>,
<Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>
Create
</Button>
</Form>
</div>
);
}
}
export default CreateForm
我有不同数据类型的字段,它来自API响应,需要相应地进行输入。
请帮我处理handleOk函数,了解如何使用用户输入的变量收集表单字段,因为当前的变量不起作用。
答案 0 :(得分:0)
而不是处理Button
的{{1}}事件,
onClick
使用<Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>
Create
</Button>
的{{1}}事件来捕获值,同时将Form
移动到表单
onSubmit
并将loading
的类型更改为<Form
className="ant-advanced-search-form"
loading="{loading}"
onSubmit="{this.handleOk}"
>
Button
有关详细信息,请参阅Form | Semantic UI docs。