React功能组件的功能或粗箭头? [英] Function or fat arrow for a React functional component?

查看:154
本文介绍了React功能组件的功能或粗箭头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不禁想知道在React函数组件中使用普通函数和粗箭头之间是否有优势

I can't help but wondering if there's any advantage between using plain functions and fat arrows for React functional components

const MyMainComponent = () => (
  <main>
    <h1>Welcome to my app</h1>
  </main>
)

function MyMainComponent() {
  return (
    <main>
      <h1>Welcome to my app</h1>
    </main>
  )
}

这两种工作当然都很好,但是有推荐的写法吗?有任何论点支持另一方吗?

Both work of course perfectly fine but is there a recommended way to write those ? Any argument in favor of one or the other ?

我知道普通javascript函数(即上下文,堆栈跟踪,return关键字等)之间的差异,这些差异可能会影响您对函数的使用方式.但是我纯粹是用React组件来问这个问题.

I am aware of the differences when it comes to plain javascript functions (i.e. context, stack trace, return keyword, etc.) that can have an impact for the kind of use you have for functions. However I am asking the question purely in terms of React components.

推荐答案

没有实际区别.

箭头允许跳过return关键字,但不能从提升中受益.这样,对于ES6目标,输出的详细程度会降低,但在转译至ES5时,则会产生更多的冗长输出,因为将函数分配给了变量:

An arrow allows to skip return keyword, but cannot benefit from hoisting. This results in less verbose output with ES6 target but more verbose output when transpiled to ES5 , because a function is assigned to a variable:

var MyMainComponent = function MyMainComponent() {
  return React.createElement(
    "main",
    null,
    React.createElement("h1", null, "Welcome to my app")
  );
};

压缩后的JS文件中的开销为6个字节,通常不考虑这一点.

The overhead is 6 bytes in minified and not gzipped JS file, this consideration can be generally ignored.

由于优化,导出箭头时不一定需要详细说明:

Verbosity is not necessarily the case when an arrow is exported, due to optimizations:

var MyMainComponent = (exports.MyMainComponent = function MyMainComponent() {
  return React.createElement(
    "main",
    null,
    React.createElement("h1", null, "Welcome to my app")
  );
});

这篇关于React功能组件的功能或粗箭头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆