反应道具类型-如果道具类型错误,是否重置为默认值?

时间:2019-05-08 08:46:55

标签: javascript reactjs react-proptypes

假设我在React中使用按钮:

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

在我的Button类中,我有以下代码:

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

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

这很好。如果我未指定任何道具,则默认为primary。但是如果我写:

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

...我希望我的代码注意到不是这是有效的道具类型(不是primarysecondary),因此会自动将其设置为默认值。

  • 这可能吗?还是不建议这样做?

3 个答案:

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