React Prop Types - 在错误的道具类型上,重置为默认值?

React Prop Types - On false prop type, reset to default?

假设我在 React 中使用一个按钮:

<Button appearance="primary"> Primary </Button>

在我的按钮 Class 中,我有以下代码:

StyledButton.defaultProps = {
  appearance: 'primary'
};

StyledButton.propTypes = {
  appearance: propTypes.oneOf(['primary', 'secondary']),
};

这很好用。如果我不指定任何道具,它将默认为 primary。但是如果我写:

<Button appearance="blabla"> Primary </Button>

...我希望我的代码注意到这是 不是 有效的道具类型(既不是 primary 也不是 secondary)等等自动将其设置回默认值。

试试下面的方法,

    const StyledButton = ({appearance}) => {
       const appearanceUpdate = ['primary', 'secondary'].includes(appearance) ? appearance : "primary"
       return <Button appearance={appearanceUpdate}> Primary </Button>
    }

方法一

如果您想向用户显示替代消息,则使用该无效道具。在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>
}

方法二

如果你想抛出一个错误(在控制台);

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>
}

我认为这不是 PropTypes 的用例,而应该在组件本身中完成。 我会这样做:

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)
}