如果不需要propType,为什么ESLint要为其提供默认prop?

时间:2018-09-14 12:49:19

标签: reactjs eslint airbnb

const propTypes = {
  lable: PropTypes.string,
};
const defaultProps = {};

为什么ESLint不需要提供标签的默认值? (react / require-default-props) 我在扩展airbnb

3 个答案:

答案 0 :(得分:1)

我已经得出结论,当您可以使用 ES6 默认值代替时,为组件定义 defaultProps 没有有意义的好处。

我发现的唯一好处 (from the docs):

<块引用>

defaultProps 相对于代码中自定义默认逻辑的一个优势是 defaultProps 在 PropTypes 类型检查发生之前由 React 解析,因此类型检查也将适用于您的 defaultProps。 对于无状态也同样适用函数组件:默认函数参数的行为与 defaultProps 不同,因此仍然首选使用 defaultProps。

所以有一些预期的好处,但我认为实现 defaultProps 所需的冗长和时间使得它们不值得,除非您真的需要此功能。


例外:

我们确实对一些组件进行了例外处理并定义了 OurComponent.defaultProps,但即便如此,我们还是有选择地这样做。我们只在我们将使用 ES6 默认值的地方定义它们。我们不会为每个非必需道具定义默认值。

值得注意的是,相关规则包含在eslint-plugin-react“推荐”配置中。

答案 1 :(得分:0)

我有同样的问题。我以此为解决方案。

const propTypes = {
  lable: PropTypes.string,
};
const defaultProps = {
  lable: '',
};

答案 2 :(得分:-1)

使用ReactJS示例消除eslint(react/require-default-props)

const MyComponent extends React.Component {
  ...
}

MyComponent.defaultProps = {
  el: '',
  quantity: 0,
  arr: [],
  ...
}

MyComponent.propTypes = {
  el: PropTypes.string,
  quantity: PropTypes.number,
  arr: PropTypes.array,
  ...
}

export default MyComponent