加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 如何声明React PropTypes XOR

发布时间:2020-12-15 20:10:52 所属栏目:百科 来源:网络整理
导读:我曾经用多个配置编写组件例如: 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,/
我曾经用多个配置编写组件例如:

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选项将是有用的.我读了https://facebook.github.io/react/docs/reusable-components.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",["widthOffset"])
};

它正在工作:用户必须使用或者widthOffset和minWidth声明.但我认为更嵌入式的解决方案将简化声明,并将改善引发的错误.

我在react github上发布了这个需求

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读