san*_*a-p 36 javascript wai-aria reactjs
我有一个组件<Button>.
如果组件没有this.props.children,我想将prop设置ariaLabel为isRequired,否则可以是可选的.我怎么做?
ariaLabel 道具不需要:
<Button>Add to bag</Button>
Run Code Online (Sandbox Code Playgroud)
ariaLabel 必须要求道具:
<Button ariaLabel="Add to bag" icon={ favorite } />
Run Code Online (Sandbox Code Playgroud)
if this.props.children和this.props.ariaLabel是空的,它会抛出一个错误,说this.props.ariaLabel是的isRequired
<Button icon={ favorite } />
Run Code Online (Sandbox Code Playgroud)
propTypes:
Button.propTypes = {
/** icon inside Button. */
icon: React.PropTypes.object,
/** Content inside button */
children: React.PropTypes.node,
/** Aria-label to screen readers */
ariaLabel: React.PropTypes.string, /*isRequired if children is empty */
};
Run Code Online (Sandbox Code Playgroud)
谢谢
chi*_*lli 93
你不需要另一个库,'prop-types'提供了这个开箱即用的功能.请参阅https://facebook.github.io/react/docs/typechecking-with-proptypes.html
例:
import PropTypes from 'prop-types';
//.......
ExampleComponent.propTypes = {
showDelete: PropTypes.bool,
handleDelete: function(props, propName, componentName) {
if ((props['showDelete'] == true && (props[propName] == undefined || typeof(props[propName]) != 'function'))) {
return new Error('Please provide a handleDelete function!');
}
},
}
Run Code Online (Sandbox Code Playgroud)
Kel*_*oya 15
这可能正是您所需要的:https://github.com/thejameskyle/react-required-if
在您的情况下,您的propTypes将是:
import requiredIf from 'react-required-if';
Button.propTypes = {
/** icon inside Button. */
icon: React.PropTypes.object,
/** Content inside button */
children: React.PropTypes.node,
/** Aria-label to screen readers */
ariaLabel: requiredIf(React.PropTypes.string, props => !props.children), /*isRequired if children is empty */
};
Run Code Online (Sandbox Code Playgroud)
要添加到上述@chickenchilli的答案中,您可以将其抽象为一个更方便的辅助函数,如下所示:
export default function conditionalPropType(condition, message) {
if(typeof condition !== 'function') throw "Wrong argument type 'condition' supplied to 'conditionalPropType'";
return function(props, propName, componentName) {
if (condition(props, propName, componentName)) {
return new Error(`Invalid prop '${propName}' '${props[propName]}' supplied to '${componentName}'. ${message}`);
}
}
}
Run Code Online (Sandbox Code Playgroud)
import PropTypes from 'prop-types';
import conditionalPropType from './conditionalPropType';
[...]
MyComponent.propTypes = {
conditionProp: PropTypes.bool,
dependentProp: conditionalPropType(props => (props.condition && typeof(props.someProp) !== 'boolean'), "'dependentProp' must be boolean if 'conditionProp' is true"),
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11029 次 |
| 最近记录: |