我是新来的,我希望代码尽可能短。我们正在编写带有许多道具的反应组件。问题是我的同事不断填写代码,这对我来说似乎非常不必要。那么将 null 设置为所有可用值还是仅使用 propTypes 来定义属性类型是否正确?因为我没有看到这样的使用示例,我认为这是不好的做法。
FormAutonumeric.defaultProps = {
validationRules: null,
onBlur: null,
onFocus: null,
inputClasses: null,
showErrors: false,
numericType: null,
isFormValid: null,
placeholder: null,
onChange: null,
disabled: null,
children: null,
vMin: null,
vMax: null,
prefix: null,
suffix: null
};
FormAutonumeric.propTypes = {
validationRules: PropTypes.shape({
[PropTypes.string]: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.bool
])
}),
onBlur: PropTypes.func,
onFocus: PropTypes.func,
inputClasses: PropTypes.string,
showErrors: PropTypes.bool,
numericType: PropTypes.string,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
isFormValid: PropTypes.func,
id: PropTypes.string.isRequired,
placeholder: PropTypes.string,
onKeyUp: PropTypes.func.isRequired,
onChange: PropTypes.func,
disabled: PropTypes.bool,
children: PropTypes.element,
vMin: PropTypes.string,
vMax: PropTypes.string,
prefix: PropTypes.string,
suffix: PropTypes.string
};
Run Code Online (Sandbox Code Playgroud)
我同意 Raul Rene 的评论。任何未使用的道具都可能undefined不会对您的代码产生任何影响,除非您进行严格的检查,例如myProp !== null或其他。
如果你想继续使用defaultProps但仍然稍微缩短你的代码,你总是可以将isRequired属性添加到那些对你的组件工作绝对必要的道具中。例如,你的组件可能不会如预期,如果工作onBlur和onFocus道具都没有通过,而它可能会,如果正常工作children或者disabled没有在显式传递。
以下是此更改的样子:
onBlur: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
Run Code Online (Sandbox Code Playgroud)
并从您的defaultProps定义中删除这些道具。如果“需要”将道具显式传递给组件,则“回退”道具没有意义。
我不知道您的代码如何查找您的组件,但是道具名称表明您的defaultProps定义可以通过此更改至少减少一半。
| 归档时间: |
|
| 查看次数: |
902 次 |
| 最近记录: |