【发布时间】:2018-11-18 05:40:25
【问题描述】:
我是新来的反应,我想尽可能简短地编写代码。我们正在编写带有许多道具的反应组件。问题是我的同事一直在填写代码,这对我来说似乎非常不必要。那么将 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
};
【问题讨论】:
-
这可能是一个个人意见类型的问题,而不是对最佳实践的呼吁,但在几个大型 React 项目之后,我更喜欢只声明 PropTypes 的简短版本。我认为使用
nullbcundefined之类的默认值没有意义,将呈现相同的内容。我只在真正需要时才声明 defaultProps。 -
如果没有必要,我不会将默认属性设置为 null。我只在需要时才这样做,即如果您有一个布尔属性并且默认将其设置为 false,直到您在代码中的某个位置将其设置为 true。我想说无论如何都不需要将所有属性设置为 null。
-
我看到你已经为你的问题开了一个赏金。以下答案没有回答您的问题吗?答案中没有您特别希望得到的任何东西?
-
@Chris 我只是想要更多的关注。否则你的答案是好的。
标签: reactjs