Javascript 如何在react native中从动态UI向服务器上载数据
在这段代码中,我得到了一些数组值,它是动态的。基于该值,我生成UI。此值可能会根据用户界面的变化而变化 现在我必须上传所有点击按钮的数据到服务器上,我感到困惑 就像我们有3个静态字段一样,我可以创建3个状态,通过使用它,我可以将该值传递给API 但在这里,当我生成动态UI时,我如何获取价值并上传 下面是我生成动态表单的数组值Javascript 如何在react native中从动态UI向服务器上载数据,javascript,reactjs,react-native,ecmascript-6,Javascript,Reactjs,React Native,Ecmascript 6,在这段代码中,我得到了一些数组值,它是动态的。基于该值,我生成UI。此值可能会根据用户界面的变化而变化 现在我必须上传所有点击按钮的数据到服务器上,我感到困惑 就像我们有3个静态字段一样,我可以创建3个状态,通过使用它,我可以将该值传递给API 但在这里,当我生成动态UI时,我如何获取价值并上传 下面是我生成动态表单的数组值 formFields: Array(8) 0: key: "dateOfBirth" label: "Date o
formFields: Array(8)
0:
key: "dateOfBirth"
label: "Date of Birth"
model: "model.dateOfBirth"
name: "dateOfBirth"
placeHolder: "DD/MM/YYYY"
position: "1"
required: "true"
type: "date"
__typename: "FormFields"
__proto__: Object
1:
key: "lastRechargedAmount"
label: "Last RCC Amt."
model: "model.lastRechargedAmount"
name: "lastRechargedAmount"
placeHolder: "Amount in Naira"
position: "2"
required: "false"
type: "text"
__typename: "FormFields"
__proto__: Object
2:
key: "stateOfOrigin"
label: "State of Origin"
model: "model.stateOfOrigin"
name: "stateOfOrigin"
placeHolder: "State of origin"
position: "3"
required: "true"
type: "parentSelect"
__typename: "FormFields"
__proto__: Object
3: {type: "childSelect", model: "model.lgaOfOrigin", label: "LGA of Origin", placeHolder: "Enter Lga of origin", key: "lgaOfOrigin", …}
4:
key: "frequentlyDialledNumbers1"
label: "Freq.Dialled No"
model: "model.frequentlyDialledNumbers"
name: "frequentlyDialledNumbers1"
placeHolder: "frequently dialled MSISDN"
position: "5"
required: "true"
type: "text"
__typename: "FormFields"
__proto__: Object
5: {type: "text", model: "model.frequentlyDialledNumbers", label: "Freq.Dialled No", placeHolder: "frequently dialled MSISDN", key: "frequentlyDialledNumbers2", …}
6: {type: "text", model: "model.frequentlyDialledNumbers", label: "Freq.Dialled No", placeHolder: "frequently dialled MSISDN", key: "frequentlyDialledNumbers3", …}
7: {type: "text", model: "model.frequentlyDialledNumbers", label: "Freq.Dialled No", placeHolder: "frequently dialled MSISDN", key: "frequentlyDialledNumbers4", …}
length: 8
下面的代码用于生成UI,按下按钮时调用函数validateUser()。按下按钮时,我必须获取所有值并发送此函数
class CustomerEvalidation extends Component {
constructor(props) {
super(props);
const { eValidationMasterData } = this.props;
this.state = {
selectedRow: -1,
disableBtn: true,
showSimSwapReason: false,
dateOfBirth: currentDate,
lastName: '',
lgaValue: eValidationMasterData.masterData.lga[0].code,
stateValue: eValidationMasterData.masterData.lga[0].state.name,
stateCode: eValidationMasterData.masterData.lga[0].state.code,
isModalVisible:false
};
}
componentWillUnmount() {
this.setState({
showSimSwapReason: false
});
}
lgaChanged = (key, val) => {
this.handleChangeLga({ field: "lgaValue" }, val);
};
handleChangeLga = (props, e) => {
const { lga } = this.props.eValidationMasterData.masterData;
let tempObj = this.state.lgaValue;
for (let i = 0; lga[i]; i++) {
if (lga[i].code == e) {
const stateData = lga[i].state;
this.setState({
stateValue: stateData.name,
stateCode: stateData.code
})
}
}
tempObj[props.field] = e;
this.setState({ lgaValue: e });
};
validatUser = () => {
const {dateOfBirth,lgaValue,stateCode}=this.state;
const validateUser = {
dateOfBirth: dateOfBirth,
lgaValue:lgaValue,
stateCode:stateCode
}
this.props.verifySecurityQuestions(validateUser);
}
onChangeExp = (e) => {
this.setState({
dateOfBirth: e
})
}
render() {
const { dateOfBirth, lastName, lgaValue, stateValue } = this.state;
const { isCamera, loading, error, securityQuestions, eValidationMasterData,validateUser } = this.props;
const { formFields } = securityQuestions.evalidatorType[0].SelectionList[0];
const { lga } = eValidationMasterData.masterData;
let lgaOptions = [];
lga.map(({ code: value, name: label }) => {
lgaOptions.push({ value, label });
});
return (
<View style={{minHeight: deviceHeight, color:'#fff'}}>
{loading &&
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<OverlaySpinner color="#00678F" />
</View>}
{!isCamera && (
<View style={styles.container}>
{formFields.map((document, index) => {
return (
<View style={{backgroundColor: '#fff' }}
key={index}>
{document.type === 'text' && (
<View style={{ padding: 15}} >
<View style={{ flexDirection: 'row', backgroundColor: '#fff' }}>
<SmallText textColor="grey" text={document.label} />
</View>
<Item style={{ borderColor: '#00fff', borderBottomWidth: 1, marginLeft: 0 }}>
<Input
value={lastName}
keyboardType='default'
onChangeText={(lastName) =>
this.setState({ lastName: lastName.replace(/\s/g, '') })}
/>
</Item>
</View>
)
}
{document.type === 'date' && (
<View style={{ padding: 15}}>
<View style={{
flexDirection: 'row', backgroundColor: '#fff'
}}>
<SmallText textColor="grey" text={document.label} />
</View>
<Item style={{ borderColor: '#00fff', borderBottomWidth: 1, marginLeft: 0 }}>
<DatePicker
minDate={minDate}
maxDate={currentDate}
currentDate={dateOfBirth}
format={format}
width={deviceWidth}
onChange={(dateOfBirth) => this.onChangeExp(dateOfBirth)}
marginLeft={0}
/>
</Item>
</View>
)}
</View>
);
}
)}
</View>
)}
<View style={{ flexDirection: 'column', padding: 15 }}>
<View style={{ flexDirection: 'column', flex:1 }}>
<SelectField options={lgaOptions} value={lgaValue}
onChange={this.lgaChanged} that={this}
label={"LGA of Origin"} />
</View>
<View style={{ flexDirection: 'column' }}>
<View style={{ flexDirection: 'row', backgroundColor: '#fff' }}>
<SmallText textColor="grey" text={"State of Origin"} />
</View>
<Item style={{ borderColor: '#00fff', borderBottomWidth: 1, marginLeft: 0 }}>
<Input
value={stateValue}
keyboardType='default'
onChangeText={(stateValue) =>
this.setState({ stateValue: stateValue.replace(/\s/g, '') })}
/>
</Item>
</View>
<View style={{ paddingBottom: 15, marginTop: 20 }}>
<PrimaryBtn label={'Validate User'} disabled={false}
onPress={() => this.validatUser()} />
</View>
</View>
</View>
);
}
}
export default CustomerEvalidation;
类CustomerValidation扩展组件{
建造师(道具){
超级(道具);
const{eValidationMasterData}=this.props;
此.state={
selectedRow:-1,
是的,
儿子:错,
出生日期:当前日期,
姓氏:“”,
lga值:eValidationMasterData.masterData.lga[0]。代码,
stateValue:eValidationMasterData.masterData.lga[0].state.name,
状态代码:eValidationMasterData.masterData.lga[0]。状态代码,
isModalVisible:错误
};
}
组件将卸载(){
这是我的国家({
儿子:错
});
}
lgaChanged=(键,值)=>{
this.handleChangeLga({field:“lgaValue”},val);
};
handleChangeLga=(道具,e)=>{
const{lga}=this.props.eValidationMasterData.masterData;
设tempObj=this.state.lgaValue;
for(设i=0;lga[i];i++){
如果(lga[i]。代码==e){
const stateData=lga[i]。状态;
这是我的国家({
stateValue:stateData.name,
stateCode:stateData.code
})
}
}
tempObj[props.field]=e;
this.setState({lgaValue:e});
};
验证用户=()=>{
const{dateOfBirth,lgaValue,stateCode}=this.state;
常数validateUser={
出生日期:出生日期,
lgaValue:lgaValue,
stateCode:stateCode
}
这个.props.verifySecurityQuestions(validateUser);
}
onChangeExp=(e)=>{
这是我的国家({
出生日期:e
})
}
render(){
const{dateOfBirth,lastName,lgaValue,stateValue}=this.state;
const{isCamera,loading,error,securityQuestions,eValidationMasterData,validateUser}=this.props;
const{formFields}=securityQuestions.evalidatorType[0].SelectionList[0];
const{lga}=eValidationMasterData.masterData;
让选项=[];
lga.map({code:value,name:label})=>{
lgaOptions.push({value,label});
});
返回(
{加载&&
}
{!isCamera&&(
{formFields.map((文档,索引)=>{
返回(
{document.type==='text'&&(
this.setState({lastName:lastName.replace(/\s/g',)})
/>
)
}
{document.type=='date'&&(
this.onChangeExp(出生日期)}
marginLeft={0}
/>
)}
);
}
)}
)}
this.setState({stateValue:stateValue.replace(/\s/g',)})
/>
this.validateUser()}/>
);
}
}
导出默认客户验证;
对不起,我是个懒惰的编码员。。。。我会尽力回答阿布里法普
状态不是保存变量、使用/创建对象和将值推送到那里的唯一选项
var obj1={};
_on_fld_change(document,v){
obj1[document.name]=v;
}
_on_submit(){
return fetch(URL,'POST',{obj1})
}
render(){
...
return(
..
<Comp onValueChange={(v)=>this._on_fld_change(document,v)}/>
)
}
var obj1={};
_关于变更(文件,v){
obj1[文件名]=v;
}
_关于提交(){
返回获取(URL,'POST',{obj1})
}
render(){
...
返回(
..
本文件。\关于变更(文件,v)}/>
)
}
请查看我的供应商表单示例,希望您能获得大量信息
恒定数据
"formFields": [{
"id": "1",
"name": "companyname",
"label": "Company name",
"type": "input",
"placeholder": "",
"returnKeyType": "go"
},
{
"id": "2",
"name": "supplier_type",
"label": "Supplier type",
"type": "drop_down"
},
{
"id": "3",
"name": "country",
"label": "Country",
"type": "drop_down"
},
{
"id": "4",
"name": "phonenumber",
"label": "Mobile number",
"type": "input",
"placeholder": "",
"returnKeyType": "next"
},
{
"id": "5",
"name": "phonenumber1",
"label": "Landline number",
"type": "input",
"placeholder": "",
"returnKeyType": "next"
},
{
"id": "6",
"name": "email",
"label": "Email / UserID",
"type": "input",
"placeholder": "",
"returnKeyType": "next"
},
{
"id": "7",
"name": "contact_person",
"label": "Contact person",
"type": "input",
"placeholder": "",
"returnKeyType": "next"
},
{
"id": "8",
"name": "skype_id",
"label": "Skype id",
"type": "input",
"placeholder": "",
"returnKeyType": "next"
},
{
"id": "9",
"name": "notes",
"label": "Notes",
"type": "input",
"placeholder": "",
"returnKeyType": "go"
}
]
供应商形式组件
// @flow
import * as React from 'react';
import { Div, Button, InputText, DropDown } from '../../materialComponents';
import data from '../../constantData/supplier';
/* flow types
============================================================================= */
type Props = {
action: string,
editData?: ?{
companyname: string,
supplier_type_id: number | string,
country: number | string,
phonenumber: string,
phonenumber1: string,
landlord_email: string,
contact_person: string,
landlord_skype_id: string,
notes: string,
},
data: Object,
buttonLoader: boolean,
onSubmit: (data: Object) => any,
onError: (type: string, msg: string) => any,
};
type State = {
companyname: string,
supplier_type_id: number | string,
country_id: number | string,
phonenumber: string,
phonenumber1: string,
email: string,
contact_person: string,
skype_id: string,
notes: string,
};
/* ============================================================================
<SupplierForm />
============================================================================= */
class SupplierForm extends React.Component<Props, State> {
static defaultProps = { editData: null };
constructor() {
super();
this.state = {
companyname: '',
supplier_type_id: 0,
country_id: 0,
phonenumber: '',
phonenumber1: '',
email: '',
contact_person: '',
skype_id: '',
notes: '',
};
}
componentDidMount() {
const { editData, action } = this.props;
if (action === 'edit') {
const record = { ...editData };
const {
companyname,
supplier_type_id,
country,
phonenumber,
phonenumber1,
landlord_email,
contact_person,
landlord_skype_id,
notes,
} = record;
this.setState({
companyname,
supplier_type_id,
country_id: country,
phonenumber,
phonenumber1,
email: landlord_email,
contact_person,
skype_id: landlord_skype_id,
notes,
});
}
}
// for submit form
_handleSubmit = () => {
const { onError, onSubmit } = this.props;
const {
companyname,
supplier_type_id,
country_id,
phonenumber,
phonenumber1,
email,
contact_person,
skype_id,
notes,
} = this.state;
const supplier = {
companyname,
supplier_type_id,
country_id,
phonenumber,
phonenumber1,
email,
contact_person,
skype_id,
notes,
};
if (!companyname) {
onError('error', 'Please Enter Company Name');
} else if (!Number(supplier_type_id)) {
onError('error', 'Please Select Supplier Type');
} else if (!Number(supplier_type_id)) {
onError('error', 'Please Select Country');
} else if (!email) {
onError('error', 'Please Enter Email');
} else {
onSubmit(supplier);
}
};
/**
* handle picker values
* @param {string} fieldName
* @param {string} value
*/
_handlePickerValue = (pickerName: string, _id: string) => {
this.setState({
[`${pickerName}_id`]: _id,
});
};
/**
* handle input values
* @param {string} fieldName
* @param {string} value
*/
_handleInputValue = (fieldName: string, value: string) => {
this.setState({ [fieldName]: value });
};
/**
* render the all input fields
* @param {Object} dropDownData
*/
_renderInputFields = (dropDownData: Object) => {
const { formFields } = data;
return formFields.map(field => {
if (field.type === 'input') {
return (
<InputText
key={field.id}
label={field.label}
value={this.state[field.name]}
onChangeText={value => this._handleInputValue(field.name, value)}
reference={input => {
// $FlowFixMe
this[`${field.name}_ref`] = input;
}}
returnKeyType={field.returnKeyType}
// $FlowFixMe
onSubmitEditing={() => this[`${field.name}_ref`].focus()}
/>
);
}
if (field.type === 'drop_down') {
const itemData =
field.name === 'country'
? dropDownData.countries
: dropDownData[`${field.name}s`];
const selectedValue = this.state[`${field.name}_id`];
return (
<DropDown
key={field.id}
label={field.label}
data={itemData}
selectedValue={selectedValue}
onChange={value => this._handlePickerValue(field.name, value)}
/>
);
}
return null;
});
};
render() {
const { data: dropDownData, buttonLoader, action } = this.props;
const buttonTitle = action === 'add' ? 'Save' : 'Update';
return (
<Div>
{this._renderInputFields(dropDownData)}
<Button
loader={buttonLoader}
color="#FFFFFF"
backgroundColor="#21A24F"
marginVertical={10}
borderRadius={2}
iconName="save"
title={buttonTitle}
onPress={this._handleSubmit}
/>
</Div>
);
}
}
/* export
============================================================================= */
export default SupplierForm;
/@flow
从“React”导入*作为React;
从“../../materialComponents”导入{Div,Button,InputText,DropDown};
从“../../constantData/supplier”导入数据;
/*流类型
============================================================================= */
类型道具={
动作:字符串,
编辑数据?:{
companyname:string,
供应商类型标识:编号字符串,
国家:数字|字符串,
电话号码:string,
phonenumber1:字符串,
房东_电子邮件:string,
联系人:string,
房东\u skype\u id:string,
注:字符串,
},
数据:对象,
buttonLoader:布尔值,
onSubmit:(数据:对象)=>任意,
onError:(type:string,msg:string)=>any,
};
类型状态={
companyname:string,
供应商类型标识:编号字符串,
国家/地区id:number |字符串,
电话号码:string,
phonenumber1:字符串,
电子邮件:string,
联系人:string,
s