2017-04-19 30 views
0

我有一個組件,有一對夫婦功能,當單擊向上或向下按鈕時遞增或遞減數字。反應增加/減少功能只允許1向上或向下

這是我做了什麼:

... 

this.state = { 
     score: 50, //The initial number can only go up or down 1 
     clicked: 0, 
    }; 

...then 

increment() { 
    if (!this.state.voted) { 
     this.setState({ 
     score: this.state.score + 1, 
     voted: this.state.voted = 1, 
     }); 
    } 
    } 

    decrement() { 
    if (!this.state.voted) { 
     this.setState({ 
     score: this.state.score - 1, 
     voted: this.state.voted = 1, 
     }); 
    } 
    } 
} 

現在我只要一點擊其中任何一個運行是函數就會停止運轉的按鈕,但我需要的,只要它不」它的工作牛逼上漲或下跌更多的是1

所以點擊增量時和減量只能去到49

我怎樣才能做到這一點50可以去51?

+0

你需要跟蹤「狀態」的開始分數。然後你的'if'語句檢查當前分數是+/- 1而不是'voted' – gforce301

+1

爲什麼你不能在點擊後立即禁用按鈕,我的意思是,如果增加按鈕已經加1,只是禁用它,只讓減量按鈕可以被點擊。 – cabolanoz

回答

1

而不是檢查投票是否已經發生的標誌,只需檢查該值是否在正確的範圍內。這意味着你只有< 51遞增,且僅減少,如果> 49

this.state = { 
    score: 50, //The initial number can only go up or down 1 
    clicked: 0, 
}; 

increment() { 
    if (this.state.score < 51) { 
    this.setState({ 
     score: this.state.score + 1, 
    }); 
} 

decrement() { 
    if (this.state.score > 49) { 
    this.setState({ 
     score: this.state.score - 1, 
    }); 
    } 
} 

如果分數可以是任何值,則僅保留其他屬性,如defaultScore它初始化到相同的值score,和您的支票將變成score < (defaultScore + 1)score > (defaultScore - 1)