How do I write a named arrow function in ES2015?

前端 未结 8 797
余生分开走
余生分开走 2020-11-22 16:29

I have a function that I am trying to convert to the new arrow syntax in ES6. It is a named function:

function sayHello(name) {
    console         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 16:46

    It appears that this will be possible with ES7: https://babeljs.io/blog/2015/06/07/react-on-es6-plus#arrow-functions

    The example given is:

    class PostInfo extends React.Component {
      handleOptionsButtonClick = (e) => {
        this.setState({showOptionsModal: true});
      }
    }
    

    The body of ES6 arrow functions share the same lexical this as the code that surrounds them, which gets us the desired result because of the way that ES7 property initializers are scoped.

    Note that to get this working with babel I needed to enable the most experimental ES7 stage 0 syntax. In my webpack.config.js file I updated the babel loader like so:

    {test: /\.js$/, exclude: /node_modules/, loader: 'babel?stage=0'},
    

提交回复
热议问题