首页 > 解决方案 > 将子组件数据合并到父组件内的一个对象中

问题描述

我正在尝试从其父组件内的同一子组件发送的数据创建对象。

在父级中的提交按钮上,获取所有子组件数据并将其附加到一个对象中并将其传递给父级。

父组件

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
}

标签: javascriptreactjsobjectmaterial-uireact-hooks

解决方案


推荐阅读