创建自定义 PropType,以扩展 react 中的默认 PropType
Creating custom PropTypes that extend default PropTypes in react
我正在尝试创建一个自定义 PropType,用于检查数组是否具有数值且长度为 2(并且对数字的顺序有一些限制)。
显然,我可以对前两个约束做Array.PropType.arrayOf(Array.PropType.number)
。
我想在我的自定义 PropType 中重用它(而不是推出我自己的数字和数组检查)。
我该怎么做?
React.PropTypes.arrayOf( React.PropTypes.number )
只返回一个函数,因此您可以改为提供自己的函数来执行验证。
您的函数将传递三个参数:props, propName, componentName
请参阅文档中的 React.PropType 中显示的倒数第二个示例。
因此,应该满足约束的函数是:
function isTwoElementArrayOfNumbers( props, propName, componentName ){
var _array = props[ propName ];
if( _array && _array.constructor === Array && _array.length === 2 ){
if( !_array.every(
function isNumber( element ){
return typeof element === 'number';
})
){
return new Error('elements must be numbers!');
}
}
else{
return new Error('2 element array of numbers not provided!');
}
}
...in your react element
propTypes:{
numArray: isTwoElementArrayOfNumbers
},
我不知道
扩展它们,我不确定这是否可能。
但是您可以将上述内容存储为导出的常量,并使用它来组合其他 propType 的属性(但我想您可能已经知道这一点):
export const CustomProp = Array.PropType.arrayOf(Array.PropType.number)
export const OtherCustomProp = contains({
foo: React.PropTypes.string,
bars: CustomProp
});
相关文章:
- React重新渲染但未显示正确的组件
- React组件等待所需道具进行渲染
- React中的数据集表示
- Webpack开发服务器和React服务器端渲染
- React Redux错误页面管理
- react.js中的密钥绑定
- 如何在react js中将值从一个组件发送到另一个组件
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- React:按键的性能提升
- 如何在react js中从一个页面导航到另一个页面
- React组件-设置页面标题
- 警告:失败的propType:类型为“array”的无效prop应为React的“object”
- Bad Errors for PropType (React)
- 创建自定义 PropType,以扩展 react 中的默认 PropType
- React Router服务器端呈现错误:警告:失败的propType:在“RoutingContext”中未指定必需的
- react本机选项卡导航器npm模块在静态proptype中显示意外的令牌
- React JS ' proptype '验证器运行两次
- PropType 在 React 中的重要性是什么?
- React警告传递值为null的prop,其中prop的PropType不是必需的
- React PropType元素类型