gpt4 book ai didi

reactjs - 我应该将默认 react 属性设置为 null

转载 作者:行者123 更新时间:2023-12-04 02:59:16 24 4
gpt4 key购买 nike

我是新来的,我希望代码尽可能短。我们正在编写带有许多 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com