2017-02-20 20 views
1

我跟蹤生日,需要更改用戶輸入的狀態,但問題是我的生日數組的新實例是在用戶鍵入覆蓋狀態時創建的。任何想法如何改變生日指數狀態,即當他們進入月份位置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 }); 
    } 
    } 

回答

1

原因是要創建DOB的新實例,並通過新創建的array替換狀態的價值的價值onchange,而不是從國家複製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 }); 
} 

檢查工作fiddlehttps://jsfiddle.net/drffr0ww/

+0

這是行不通的。這是發生了什麼https://puu.sh/uc7tq/e8646eab30.png – joethemow

+0

更新我的答案與工作小提琴檢查:) –

相關問題