我正在跟踪生日并需要在用户输入时更改状态,但问题是当用户键入覆盖状态时创建生日数组的新实例。任何想法如何改变生日指数状态,即当他们进入月份位置0时将改变,日期位置1将改变,年份位置3将改变。
this.state = {
dob : ["", "", ""]
};
onInputChange(event) {
const type = event.target.name;
var dob = ["", "", ""];
if(type == "month") {
birthday[0] = event.target.value;
this.setState({ dob });
} else if(type == "date") {
birthday[1] = event.target.value;
this.setState({ dob });
} else if(type == "year"){
birthday[2] = event.target.value;
this.setState({ dob });
}
}
答案 0 :(得分:1)
原因是您创建新的dob实例的任何值的onchange
,并用新创建的array
替换state的值,而不是从状态替换dob的值然后更新特定值,并将array
恢复到状态,写成这样:
this.state = {
dob : ["", "", ""]
};
onInputChange(event) {
const type = event.target.name;
var dob = this.state.dob.slice();
if(type == "month") {
dob[0] = event.target.value;
} else if(type == "date") {
dob[1] = event.target.value;
} else if(type == "year"){
dob[2] = event.target.value;
}
this.setState({ dob });
}
检查工作fiddle
:https://jsfiddle.net/drffr0ww/