假设我在React中使用按钮:
<Button appearance="primary"> Primary </Button>
在我的Button类中,我有以下代码:
StyledButton.defaultProps = {
appearance: 'primary'
};
StyledButton.propTypes = {
appearance: propTypes.oneOf(['primary', 'secondary']),
};
这很好。如果我未指定任何道具,则默认为primary
。但是如果我写:
<Button appearance="blabla"> Primary </Button>
...我希望我的代码注意到不是这是有效的道具类型(不是primary
或secondary
),因此会自动将其设置为默认值。
答案 0 :(得分:1)
方法1
如果您想向用户显示替代消息,则使用无效的道具。在HTML中
const StyledButton = ({ appearance }) => {
const isValid = ['primary', 'secondary'].includes(appearance);
if (!isValid) {
return <p>Invalid prop appearance can only be primary or secondary<p>
}
return <Button appearance={appearance}> Primary </Button>
}
方法2
如果要抛出错误(在控制台中);
const StyledButton = ({ appearance }) => {
const isValid = ['primary', 'secondary'].includes(appearance);
if (!isValid) {
throw new Error("Invalid propType appearance, can only be primary or secondary")
}
return <Button appearance={appearance}> Primary </Button>
}
答案 1 :(得分:0)
尝试以下方法
const StyledButton = ({appearance}) => {
const appearanceUpdate = ['primary', 'secondary'].includes(appearance) ? appearance : "primary"
return <Button appearance={appearanceUpdate}> Primary </Button>
}
答案 2 :(得分:-1)
我不认为这是PropType的用例,而是应该在组件本身中完成。 我会这样做:
const options = ['primary', 'secondary'];
const defaultOption = options[0];
const StyledButton = ({ appearance }) => {
if (!options.includes(appearance)) appearance = defaultOption;
// ... actual implementation
}
StyledButton.defaultProps = {
appearance: defaultOption,
}
StyledButton.propTypes = {
appearance: PropTypes.oneOf(options)
}