React 函数组件:const 与 function

2025-06-10

React 函数组件:const 与 function

最近我一直在优化我们的应用性能,因此,我开始深入研究 JavaScript 的本质。我思考的一件事是,像这样声明组件,两者之间是否存在真正的区别:

const MyComponent = () => {
    return(
      ..
    )
}
Enter fullscreen mode Exit fullscreen mode

对比

function MyComponent() {
    return(
      ..
    )
}
Enter fullscreen mode Exit fullscreen mode

这种形式的function语法稍微短一些。

进而?

有时,我们可以像这样编写箭头函数:

const MyComponent = () => (...)
Enter fullscreen mode Exit fullscreen mode

如果我们在箭头后面放置普通括号,则不需要写return。因此,如果我们可以立即返回,它会更短。

进而?

我看到人们谈论的另一件事是export组件。

export default function MyComponent() {}
Enter fullscreen mode Exit fullscreen mode

对比

const MyComponent = () => {}

export default MyComponent
Enter fullscreen mode Exit fullscreen mode

函数语法使我们能够默认导出组件。

然后呢?(兄弟,我的车迷们在哪里?)

提升

事实证明,最大的原因(据我所知)是由于代码提升。让我们看一个符合有效语法的例子:

// I like to write my components before I use them

const MyComponent = () => {}

const AlsoMyComponent = () => {}

const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)
Enter fullscreen mode Exit fullscreen mode

然后呢?让我们看看无效的语法:

const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)
// I like to keep my components at the bottom

const MyComponent = () => {}

const AlsoMyComponent = () => {}
Enter fullscreen mode Exit fullscreen mode

此示例👆将导致你的 linter 抛出错误。因为组件在声明之前就被使用了。

因此,如果您喜欢将组件保留在底部,并在声明它们之前使用它们,我们可以使用函数语法编写它们,并将它们提升到文件的顶部。

 const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)
// I like to keep my components at the bottom

function MyComponent() {}

function AlsoMyComponent() {}
Enter fullscreen mode Exit fullscreen mode

这个例子👆不会用到你的 linter,因为当我们运行文件时,它在 JavaScript 引擎中看起来会像这样:

// Components are hoisted to the top.

function MyComponent() {}

function AlsoMyComponent() {}

 const App = () => (
    <>
      <MyComponent />
      <AlsoMyComponent />
    </>
)
// I like to keep my components at the bottom

👀 where did they go?
Enter fullscreen mode Exit fullscreen mode

进而?

就是这样!我觉得……?如果你有和我不同的想法,或者知道更多区别,请告诉我!

鏂囩珷鏉ユ簮锛�https://dev.to/ugglr/react-function-components-const-vs-function-2kj9
PREV
YouTube 为何总能用完存储空间?这不仅仅是云的功劳!
NEXT
使用 namae.dev 为您的应用起一个漂亮的名字 namae 支持的平台名称建议开源结论