React.js:如何结合自定义函数与Shape校验PropTypes数组结构及长度
Combine Array Length and Structure Validation in Custom PropTypes
Got it, let's merge both the array structure check and length validation into one custom PropTypes function. The key here is to reuse the existing shape validation logic you already have, so you don't have to rewrite all those property checks manually.
Step-by-Step Solution
First, define your original structure validator as a reusable variable—this lets us call it inside our custom function:
// Reuse your existing shape validation logic const dataSourceStructure = PropTypes.arrayOf( PropTypes.shape({ share: PropTypes.number, visibleInLegend: PropTypes.bool, order: PropTypes.number, color: PropTypes.string }) );
Then, create your unified custom validator function that runs both checks in sequence:
dataSource: function(props, propName, componentName) { const dataSource = props[propName]; // 1. First check: Ensure the value is actually an array (prevents runtime errors) if (!Array.isArray(dataSource)) { return new Error( `Invalid prop \`${propName}\` supplied to \`${componentName}\`, expected an array. Validation failed.` ); } // 2. Second check: Run the original structure validation const structureValidationError = dataSourceStructure(props, propName, componentName); if (structureValidationError) { return structureValidationError; } // 3. Third check: Verify array length is exactly 2 if (dataSource.length !== 2) { return new Error( `Invalid array length \`${dataSource.length}\` (expected 2) for prop \`${propName}\` supplied to \`${componentName}\`. Validation failed.` ); } // If all checks pass, return nothing (undefined = validation success) }
How It Works
- Array Type Guard: We first confirm the prop is an array to avoid errors when accessing
.lengthor running the structure validator. - Reuse Existing Structure Checks: Instead of rewriting all the
shapevalidations, we call your pre-defined structure validator and pass through any error it generates. - Length Validation: Finally, we check if the array length matches your requirement of exactly 2, returning a targeted error if it doesn't.
This unified function will catch both invalid array structures and incorrect lengths, returning clear, specific errors for each case.
内容的提问来源于stack exchange,提问作者Zied Hf
相关产品推荐
相关产品推荐

