我应该对功能组件使用 _myMethod 吗?

Should I be using _myMethod for functional components?

最近在博客上看到很多React函数式组件中的方法都带有下划线的例子。我也在基于 class 的组件中看到了这一点,并被告知这意味着它们是私有的 (?)。

但是functional组件内部函数已经是private的,在组件之外是不可访问的,对吧?

示例:


function MyComponent({ propOne }) {

   const _getData() {
      /// Why does this have an _underscore on it?
   }
   return (
        <div>a div</div>
    )
}

这是 Airbnb React/JSX 风格指南 (version 2019.05.24) 实际警告反对的命名约定:

  • Do not use underscore prefix for internal methods of a React component.

Why? Underscore prefixes are sometimes used as a convention in other languages to denote privacy. But, unlike those languages, there is no native support for privacy in JavaScript, everything is public. Regardless of your intentions, adding underscore prefixes to your properties does not actually make them private, and any property (underscore-prefixed or not) should be treated as being public. See issues #1024, and #490 for a more in-depth discussion.

简而言之:

  • 表示private方法的underscore是从其他语言借来的。
  • 它不会改变方法本身。
  • 表明该方法是private并阻止其使用。

是否遵守约定由你决定。没有必要。如果你遵循上面引用的风格指南,你不应该。但是,这也取决于您为之工作/与之共事的人,例如。 G。如果公司使用带有前导下划线的样式指南来表示 private 属性。


此约定的另一种语言示例 - Python。来自 Naming Convention:

_single_leading_underscore

This convention is used for declaring private variables, functions, methods and classes.

_functionName 并不意味着私有,它只是一种最佳实践。

如果有兴趣编写自定义钩子,React 文档建议在钩子名称前加上前缀“use”,例如:useCustomeHook https://reactjs.org/docs/hooks-custom.html

函数式组件是一个很小的函数,在 ReactJs 中只接受 props 和 return HTML。

正如Jeanne Dark所说,这只是一种命名约定。这当然取决于您如何输入代码,但我不建议使用下划线前缀,因为您可以自己看到该函数是私有的,没有下划线。

您可以在 W3 schools, or maybe even more trustworthy, googles JavaScript style guide 上阅读有关 JS 命名约定的信息。