2016-03-09 68 views
5

我以前寫有多個配置的部件。例如:如何聲明作出反應PropTypes XOR

ResponsiveTable.PropTypes = { 
    width: React.PropTypes.number, //used if widthOffset and minWidth are undefined 
    widthOffset: React.PropTypes.number, //used if width is undefined 
    minWidth: React.PropTypes.number, //used if width is undefined 
}; 

我如何可以聲明只有當我鼻涕已經等道具設置使用的道具?

A XOR選項將是有用的。我讀https://facebook.github.io/react/docs/reusable-components.html但它沒有幫助。

任何想法?

回答

2

Solution需要:

React.PropTypes.oneOfType([ 
    React.PropTypes.shape({ 
     width: React.PropTypes.number.isRequired 
    }), 
    React.PropTypes.shape({ 
     widthOffset: React.PropTypes.number, 
     minWidth: React.PropTypes.number.isRequired 
    }), 
]) 
+0

看起來這隻會工作的,比方說屬性,對象傳遞給您的組件的XOR校驗,而不是到通過你的組件的道具的XOR驗證。我是否誤解了這一點和/或者您是否有更多關於如何使用此解決方案來解決您的原始問題的詳細信息? – aarontam

+0

是的,這個更簡單的解決方案需要測試包含寬度,寬度和寬度的特定道具。它強制你包裝屬性以測試特定的道具。 –

2

我試過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