简体   繁体   English

无状态反应函数的首选语法是什么? 为什么?

[英]What is the preferred syntax for a stateless react function? Why?

Method 1:方法一:

const BasicProfileInfo = (props: BasicProfileInfoProps) => {
    return (
            <MainContainer>
              {....}
            </MainContainer>
    )
}

Method 2:方法二:

function BasicProfileInfo(props: BasicProfileInfoProps){
    return (
            <MainContainer>
              {....}
            </MainContainer>
    )
}

Project Environment:项目环境:

  • babel-eslint: 8.0.2 babel-eslint: 8.0.2
  • babel-plugin-transform-class-properties: 6.24.1 babel-plugin-transform-class-properties: 6.24.1
  • babel-preset-es2015: 6.24.1 babel-preset-es2015: 6.24.1
  • babel-preset-react-native: 4.0.0 babel-preset-react-native: 4.0.0
  • react: 16.0.0反应:16.0.0
  • react-native: 0.48.4反应原生:0.48.4
  • mobx: 3.3.1手机:3.3.1
  • mobx-react: 4.3.3 mobx-反应:4.3.3

Arrow function can be shortened to implied return:箭头函数可以缩写为隐含返回:

const BasicProfileInfo = (props: BasicProfileInfoProps) => (
    <MainContainer>
      {....}
    </MainContainer>
);

But it has a bit more footprint in ES5 output than regular function declaration, because an arrow is transpiled to regular function any way:但是它在 ES5 输出中比常规函数声明有更多的足迹,因为箭头以任何方式转换为常规函数:

var BasicProfileInfo = function BasicProfileInfo(props) { return ... }

This is the only difference between them as stateless components.这是它们作为无状态组件的唯一区别。 Arrow functions don't have their own this and arguments , but this isn't the case.箭头函数没有自己的thisarguments ,但事实并非如此。

One advantage of using the 'arrow function' notation is that arrow functions don't have their own this value , which is useful if you want to preserve this from an outer function definition.使用“箭头函数”表示法的一个优点是箭头函数没有自己的this,如果您想从外部函数定义中保留this ,这很有用。

But, if your component is stateless, this doesn't matter, so it doesn't matter which one you use.但是,如果您的组件是无状态的,这无关紧要,因此您使用哪一个都无关紧要。

React components will use the function name as the displayName in debug messages and the developers console. React 组件将使用函数名称作为调试消息和开发人员控制台中的displayName The default displayName is Component , which is much less useful.默认的 displayName 是Component ,它的用处要小得多。 This alone I think is enough to always prefer explicitly named functions (Method 2).我认为仅此一项就足以始终更喜欢显式命名的函数(方法 2)。

EDIT: As noted below, either of OP's methods will result in the displayName being populated correctly.编辑:如下所述,OP 的任何一种方法都会导致正确填充 displayName。 The only situation that it will not is when exporting truly anonymous functions like: export default () => {} .唯一不会出现的情况是在导出真正的匿名函数时,例如: export default () => {} So the other answers here are more relevant.所以这里的其他答案更相关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM