首页 > 解决方案 > 如何声明 proptypes 以验证特定字符串的数组?

问题描述

传递给组件的值可以是字符串数组。该字符串表示不同的方向:top, right, bottom, left.

如何为组件指定 proptypes 以仅允许指定方向的数组?

  <Arrows
    directions=['left', 'bottom'] // accepts the array
  />
  <Arrows
   directions=['left', 'back'] // doesn't accept the array
  />

标签: javascriptreactjs

解决方案


像这样的东西应该可以完成这项工作:

directions: PropTypes.arrayOf(PropTypes.oneOf(['top', 'right', 'bottom', 'left'])),

推荐阅读