有没有更好的方法来验证一个数字是否在一定范围之内?避免编写下面这种代码。
PropTypes.oneOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
PropTypes.oneOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
}
所以对于您的情况,您可以尝试以下方法
function withinTen(props, propName, componentName) {
componentName = comopnentName || 'ANONYMOUS';
if (props[propName]) {
let value = props[propName];
if (typeof value === 'number') {
return (value >= 1 && value <= 10) ? null : new Error(propName + ' in ' + componentName + " is not within 1 to 10");
}
}
// assume all ok
return null;
}
something.propTypes = {
number: withinTen,
content: React.PropTypes.node.isRequired
}
completed: function(props, propName, componentName) {
if (props[propName]>=1 && props[propName]<=10) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
}
PropTypes.oneOf([...(new Array(10))].map((_, i) => i + 1))
// Sequence
console.log([...(new Array(5))].map((_, i) => i + 1))
// Spreading the Sequence numbers
console.log(...[...(new Array(5))].map((_, i) => i + 1))
age <= 18 && age >= 60
之间。import React from 'react'
import PropTypes from 'prop-types'
const App= (props) => {
return (
<div>
<h1>I am in the App Component!</h1>
<p>Age : {props.age >= 18 && props.age <= 60 ? props.age : false}</p>
</div>
)
}
App.propTypes = {
age : PropTypes.number
}
export default App;