我正在尝试从具有相同字段的子组件形式创建对象数组。
我正在使用react钩子来存储状态,并在JSX中使用for循环来重复子组件。
应用程序的流程=>父级-> 2个相同的子级但输入不同->创建对象数组->返回对象的父级数组
UI
Image of the form UI where Delivery Contact is same Child Component
父代码
import { ChangeDetectorRef } from '@angular/core';
constructor( private cd: ChangeDetectorRef ){}
this.commonCatalogueService.getRouteScheduleByRouteId(id)
.subscribe((data:any) => {
this.dataSource = data;
this.cd.detectChanges();
});
子代码
{[...Array(2)].map((e, i) => {
const deliveryContactDetails = deliveryContact => {
// deliveryRef[i].current.sendData()
console.log(deliveryContact);
}
return (
<React.Fragment>
<Grid item xs={12}>
<FormLabel component="legend">
Delivery Contact Person : ({i+1})
</FormLabel>
</Grid>
<DeliveryContact formNo={i+1} ref={deliveryRef[i] = useRef()} saveDelivery={deliveryContactDetails} ></DeliveryContact>
</React.Fragment>
)
})}
</React.Fragment>
必需对象
const formNo = props.formNo;
const [values, setValues] = useState({...contactObj})
const handleInputChange = ({ target }) => {
const { name, value } = target;
setValues({...values, [name]: value})
};
useImperativeHandle(ref,() => ({
sendData() {
props.saveDelivery(values);
}
}));
return(
<React.Fragment>
<Grid item xs={12} sm={6}>
<TextField
select
fullWidth
margin="dense"
id="salutation"
name={"salutation" + formNo}
fullWidth
onChange={handleInputChange}
value={values.salutation}
variant="outlined"
label="Salutation"
>
<MenuItem value={`Mr.`}>Mr.</MenuItem>
<MenuItem value={`Ms.`}>Ms.</MenuItem>
</TextField>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
id="deliveryContactName"
name={"name" + formNo}
label="Delivery Contact Name"
fullWidth
variant="outlined"
margin="dense"
onChange={handleInputChange}
value={values.deliveryContactName}
inputProps={{
maxLength: 40
}}
/>
</Grid>
)