我有一个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' />
答案 0 :(得分:1)
这是一种可能的解决方案:
this.state.services
的新对象(浅副本)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});
};