gpt4 book ai didi

javascript - react : how to check Proptypes with function and shape?

转载 作者:行者123 更新时间:2023-11-29 15:17:05 25 4
gpt4 key购买 nike

我有一个这个形状的数组:

dataSource: PropTypes.arrayOf(
PropTypes.shape({
share: PropTypes.number,
visibleInLegend: PropTypes.bool,
order: PropTypes.number,
color: PropTypes.string
})

现在,我想将长度限制为 2。我用这样的函数替换了最后一个 proptype:

dataSource: function(props, propName, componentName) {
let arrayPropLength = props[propName].length;
if (arrayPropLength !== 2) {
return new Error(
`Invalid array length ${arrayPropLength} (expected 2 for prop ${propName} supplied to ${componentName}. Validation failed.`
);
}
}

这两个检查工作正常,但是这只会测试数组的长度,我想将它们组合成一个函数?是这样的:

dataSource: function(props, propName, componentName) {
props[propName].PropTypes.shape({
share: PropTypes.number,
visibleInLegend: PropTypes.bool,
order: PropTypes.number,
color: PropTypes.string
})
let arrayPropLength = props[propName].length;
if (arrayPropLength !== 2) {
return new Error(
`Invalid array length ${arrayPropLength} (expected 2 for prop ${propName} supplied to ${componentName}. Validation failed.`
);
}
}

最佳答案

我认为在这种情况下可以使用 checkPropTypes API。您保留您的自定义函数,但您还运行 checkPropTypes 一个。

const myPropTypes = {
name: PropTypes.string,
age: PropTypes.number,
// ... define your prop validations
};

const props = {
name: 'hello', // is valid
age: 'world', // not valid
};

// Let's say your component is called 'MyComponent'

// Works with standalone PropTypes
PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
// This will warn as follows:
// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
// `MyComponent`, expected `number`.

来自这里的官方文档 https://github.com/facebook/prop-types#proptypescheckproptypes

关于javascript - react : how to check Proptypes with function and shape?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48061217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com