如何声明 React PropTypes XOR

How to declare React 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
};

如何声明只有在我已经设置了其他道具时才能使用的道具?

一个 XOR option would be usefull. I read https://facebook.github.io/react/docs/reusable-components.html 但没有帮助。

有什么想法吗?

您可以创建自定义 属性:

yourComponent.propTypes = {
  ...
  customProp: function(props, propName, componentName) {
    if(checkValid){
      return new Error('validation failed');
    } 
  }
  ...
}

这是在 React 文档中 https://reactjs.org/docs/typechecking-with-proptypes.html

我尝试了 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,或者声明 widthOffset 和 minWidth。但我认为更嵌入式的解决方案将简化声明并改善引发的错误。

我post需要react github

Solution:

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