我試過customProp。我有類似的東西:
/**
* Configure a React type to be usable only if including ot exclufing other props from component
* @param {React.PropTypes} propType current prop type
* @param {Array} excludedProps names of the props to exclude
* @param {Array} includedProps name of the props to include
*/
function propTypeXOR(propType,excludedProps,includedProps){
return(props, propName, componentName) =>{
if(props[propName]){
if(typeof props[propName] !== propType){
return new Error("Failed propType: Invalid prop `"+propName+"` of type `"+propType+"` supplied to `"+componentName+"`, expected `number`");
}else{
excludedProps.map((excludedPropName) =>{
if(props[excludedPropName]){
return new Error("forbidden prop `"+excludedPropName+"` was specified in `"+componentName+"` when using the prop `"+propName+"`");
}
})
if(includedProps){
includedProps.map((includedPropName) =>{
if(props[includedPropName]){
return new Error("required prop `"+includedPropName+"` was not specified in `"+componentName+"` when using the prop `"+propName+"`");
}
})
}
}
}else{
if(excludedProps){
var error = "";
excludedProps.map((excludedPropName) =>{
if(!props[excludedPropName]){
error+="`"+excludedPropName+"`,";
}
})
if(error!=""){
return new Error("required prop `"+propName+"` was not specified in `"+componentName+"`.It is required when props ["+error+"] are not defined.");
}
}
}
}
}
ResponsiveTable.propTypes = {
width: propTypeXOR("number",["widthOffset","minWidth"]),
widthOffset: propTypeXOR("number",["width"],["minWidth"]),
minWidth: propTypeXOR("number",["width"],["widthOffset"])
};
據工作:用戶必須聲明帶有或widthOffset和minWidth。但我認爲更嵌入式的解決方案將會緩解聲明並提高引發的錯誤。
我張貼在react github
看起來這隻會工作的,比方說屬性,對象傳遞給您的組件的XOR校驗,而不是到通過你的組件的道具的XOR驗證。我是否誤解了這一點和/或者您是否有更多關於如何使用此解決方案來解決您的原始問題的詳細信息? – aarontam
是的,這個更簡單的解決方案需要測試包含寬度,寬度和寬度的特定道具。它強制你包裝屬性以測試特定的道具。 –