【问题标题】:React handleChange push values in nested object在嵌套对象中反应 handleChange 推送值
【发布时间】:2019-05-08 10:31:26
【问题描述】:

我有一个将数据推送到道具中的 handleChange 事件

handleChange = input => e => {
    let target = e.target,
        type = target.type,
        value = target.value;

    this.setState({ 
        [input]: (type === "checkbox" ? target.checked : value) 
    });
};

在输入中,我处理更改onChange={onChange('services.cleaning')} 无论如何我可以将道具中的数据作为嵌套对象而不是“services.cleaning”推送?

onchange 事件

<Checkbox onChange={onChange('services.cleaning')} type='checkbox' name='cleaning' />

【问题讨论】:

  • 你的对象的结构是什么?
  • 你在哪里调用 onChange?粘贴sn-p
  • 我已经更新了帖子
  • 你的onChange函数在哪里?
  • 嵌套道具的深度是否总是等于 2 ?你能有这样的'prop1.prop2.prop3'吗?

标签: reactjs input onchange react-props


【解决方案1】:

这是一种可能的解决方案:

  • 首先,您需要创建this.state.services 的新对象(浅拷贝)
  • 然后你更新这个嵌套对象的 prop cleaning
  • 最后你用this.setState({services: nestedObjectCreated})更新状态

下面是对应的代码:

handleChange = propKey => e => {
   const {target} = e;
   const {type, value} = target;
   const newValue = type === "checkbox" ? target.checked : value

   const [firstProp, ...otherProps] = propKey.split('.');

   if (!otherProps.length) {
      return this.setState({[firstProp] newValue});
   }

   const nestedObject = {...this.state[firstProp]};
   otherProps.reduce(
       (acc, val, index) => {
          if (index < otherProps.length - 1) {
             return acc[val];
          }
          acc[val] = newValue;,
       },
       nestedObject
   );

   this.setState({[firstProp]: nestedObject});
};

【讨论】:

  • 哇,这正是我所需要的,感谢您解释解决方案,非常感谢
猜你喜欢
  • 2021-08-17
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
相关资源
最近更新 更多