我曾经用多个配置编写组件例如: ResponsiveTable.PropTypes = { width: React.PropTypes.number, //used if widthOffset and minWidth are undefined widthOffset: React.PropTypes.number, //used if width is undefined minWidth: React.Pr
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",["width"],["widthOffset"]) };
它正在工作:用户必须使用或者widthOffset和minWidth声明.但我认为更嵌入式的解决方案将简化声明,并将改善引发的错误.
我在react github上发布了这个需求