我是新来的,我希望代码尽可能短。我们正在编写带有许多 Prop 的 react 组件。问题是我的同事不断填写代码,这对我来说似乎非常不必要。那么将 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
};
最佳答案
我同意 Raul Rene 的评论。任何未使用的 Prop 将是 undefined
除非您进行严格的检查,否则这可能不会对您的代码产生任何影响,例如 myProp !== null
或者其他的东西。
如果您想继续使用 defaultProps
但仍然稍微缩短您的代码,您可以随时添加 isRequired
属性对您的组件工作绝对必要的那些 Prop 。例如,如果 onBlur
,您的组件可能无法按预期工作。和 onFocus
props 没有传入,而如果 children
可能会正常工作或 disabled
没有明确传入。
以下是此更改的样子:
onBlur: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
并从您的
defaultProps
中删除这些 Prop 定义。如果“需要”将 Prop 显式传递给组件,则“回退” Prop 没有意义。我不知道您的代码如何查找您的组件,但 Prop 名称表明您的
defaultProps
通过这种变化,定义至少可以减少一半。
关于reactjs - 我应该将默认 react 属性设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755925/