React PropTypes: range of numbers

前端 未结 4 2154
深忆病人
深忆病人 2021-02-14 22:31

Is there a better way to validate if a number is inside a range?

Avoiding to write

PropTypes.oneOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 
         


        
4条回答
  •  独厮守ぢ
    2021-02-14 22:48

    If it's a sequence, You can use a smart ES6. :)

    [BTW, I believe the first answer is the most appreciate, this one is just trick]

    PropTypes.oneOf([...(new Array(10))].map((_, i) => i + 1))
    

    **Explanation:** This `[...(new Array(10))].map((_, i) => i + 1)` part will give to the sequence.

    // Sequence
    console.log([...(new Array(5))].map((_, i) => i + 1))
    
    // Spreading the Sequence numbers 
    console.log(...[...(new Array(5))].map((_, i) => i + 1))

提交回复
热议问题