javascript - 将子组件数据合并到父组件内的一个对象中
问题描述
我正在尝试从其父组件内的同一子组件发送的数据创建对象。
在父级中的提交按钮上,获取所有子组件数据并将其附加到一个对象中并将其传递给父级。
父组件
const [values, setValues] = useState();
const appendFeesData = (fee) => {
const key = Object.keys(fee)[0];
const value = Object.values(fee)[0];
setValues({...values, [key]: value})
console.log("Values", values);
}
JSX 内部
{
feesObjData.map((feeObj) => {
return (
<CheckboxInputFee
ref={checkboxInputRef}
getInputValue={appendFeesData}
name={feeObj.name}
inputValue={feeObj.inputValue}
label={feeObj.label}
InputAdornment={feeObj.inputAdornment}
/>
);
})
}
子组件
const [checkboxValue, setCheckboxValue] = useState(false);
const [inputValue, setInputValue] = useState(props.inputValue);
const handleCheckbox = ({ target }) => {
setCheckboxValue(target.checked);
}
const handleInputValue = ({ target }) => {
setInputValue(target.value);
}
const createObj = () => {
const fieldName = props.name;
const value = parseInt(inputValue);
return ({
[fieldName]: value
})
}
useImperativeHandle(ref, () => ({
sendInputValue(){
const valueObj = createObj();
console.log(valueObj);
props.getInputValue(valueObj);
}
}));
JSX 内部
<Grid item xs={6}>
<FormControlLabel
control={<Checkbox
name={props.name}
checked={checkboxValue}
onChange={handleCheckbox}
color="primary"
/>}
label={props.label}
/>
</Grid>
<Grid item xs={6}>
<TextField
required
id={props.name}
name={props.name}
fullWidth
disabled={!checkboxValue}
onChange={handleInputValue}
value={inputValue}
variant="outlined"
margin="dense"
InputProps={{
startAdornment: (
<InputAdornment position="start">{props.InputAdornment}</InputAdornment>
)
}}
/>
</Grid>
appendFeesData 方法从每个子组件中获取一个参数作为fee = {name: value}
. 此方法应创建一个包含所有子组件值的对象,例如......
{
name1: value1,
name2: value2,
etc
}
解决方案
推荐阅读
- python - 使用章节编号和名称信息的嵌套章节名称字典构建器
- c# - C# 中的异步文件 I/O 开销
- mysql - UPDATE INNER JOIN 花了很长时间,然后给了我一个 Lock Wait Timeout Exceeded 错误
- javascript - axios 使用 %2c 调用更改逗号
- c# - 调用 Vendor API 5000 次的最佳方法
- r - 在 ShinyWidgets 中使用 selectizeGroup 时可以添加选项组吗?
- android - 无法从 androidx 导入 androidx.annotation.NonNull 和所有
- google-data-studio - Google Data Studio - 混合数据添加非连接字段
- ibm-cloud - 如何将外部卷连接到 IBM Cloud Code Engine
- domain-driven-design - 在用例中使用基础设施