[英]How to declare proptypes to validate an array of specific strings?
傳遞給組件的值可以是字符串數組。 該字符串表示不同的方向: top
、 right
、 bottom
、 left
。
如何為組件指定 proptypes 以僅允許指定方向的數組?
<Arrows
directions=['left', 'bottom'] // accepts the array
/>
<Arrows
directions=['left', 'back'] // doesn't accept the array
/>
這樣的事情應該可以完成這項工作:
directions: PropTypes.arrayOf(PropTypes.oneOf(['top', 'right', 'bottom', 'left'])),
你可以使用PropTypes來檢查 React props 的運行時類型。
使用PropTypes.arrayOf()
選項確保傳遞特定值的數組。 作為參數,您傳遞PropTypes.oneOf()
,它接受一組值(箭頭的方向)以從中進行選擇。
import React from 'react';
import PropTypes from 'prop-types';
class Arrow extends React.Component {
render() {
// ... do things with the props
}
}
Arrow.propTypes = {
directions: PropTypes.arrayOf(PropTypes.oneOf(['left', 'bottom']))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.