React PropTypes: range of numbers

前端 未结 4 1277
自闭症患者
自闭症患者 2021-02-14 21:56

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:36

    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))

提交回复
热议问题