Ms.*_*lib 46 javascript reactjs react-native
我在找PropType
那个意思
"这是必需的,它将是一个数字或为空"
换句话说,我现在拥有的是
PropTypes.number.isRequired
Run Code Online (Sandbox Code Playgroud)
但是如果null
传入一个值会抛出警告,但我想null
成为一个可接受的值.
ctr*_*usb 24
只需使用:
PropTypes.number
Run Code Online (Sandbox Code Playgroud)
默认情况下,所有prop类型都不是必需的(即allow null
或 undefined
),除非你弹出.isRequired
它们的末尾.
您可以在此处查看proptypes的完整文档:
目前prop-types
图书馆不允许这样做。我解决这个问题的方法是使用自定义验证功能
MyComponent.propTypes = {
nullableArray: function(props, propName, componentName) {
const { propName: data } = props;
if (data === undefined) {
return new Error(`Undefined ${propName} is not allowed`);
}
if (data !== null) {
return; //this is allow when data is loading
}
if (!_.isArray(data)) {
return new Error(`${propName} must be an array`);
}
}
};
Run Code Online (Sandbox Code Playgroud)
您可以再进一步一步来创建高阶函数以生成验证函数。这应该让您开始
generateRequiredOrNullValidationFunction = expectedType => {
if (expectedType !== "array") {
return Error(`Unexpected ${expectedType}`);
}
return function(props, propName, componentName) {
const { [propName]: data } = props;
if (data === undefined) {
return new Error(`Undefined ${propName} is not allowed`);
}
if (data !== null) {
return; //this is allow when data is loading
}
if (expectedType === "array" && !_.isArray(data)) {
return new Error(`${propName} must be an array`);
}
};
};
Run Code Online (Sandbox Code Playgroud)
在这个片段中,expectedType
是一个枚举,例如bool
,array
,number
...
归档时间: |
|
查看次数: |
24467 次 |
最近记录: |