handleInputChange = (event) => {
const target = event.target;
const type = target.type;
const value = String.prototype.trim.call(target.value);
const name = target.name;
if (type === 'checkbox') {
if (this.state.formData[name] === undefined) { // 创建
this.setState(() => ({
formData: Object.assign(this.state.formData, {
[name]: [value],
}),
}));
} else {
const valueIndex = this.state.formData[name].indexOf(value);
if (valueIndex < 0) { // 查找是否已经被勾选
this.setState((prevState) => ({
formData: Object.defineProperty(this.state.formData, [name], {
value: prevState.formData[name].concat([value]),
}),
}));
} else {
const arr = this.state.formData[name];
arr.splice(valueIndex, 1); // 去掉已经选择的
this.setState(() => ({
formData: Object.defineProperty(this.state.formData, [name], {
value: arr,
}),
}));
}
}
} else {
this.setState(() => ({
formData: Object.assign(this.state.formData, {
[name]: value,
}),
}));
}
}