Pab*_*uca 3 javascript range reactjs react-proptypes
有没有更好的方法来验证数字是否在范围内?
避免写
PropTypes.oneOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Run Code Online (Sandbox Code Playgroud)
根据文档,您可以定义customProps
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,对于您的情况,您可以尝试以下方法
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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2593 次 |
最近记录: |