繁体   English   中英

使用ES6类箭头功能

[英]Using ES6 Class Arrow Function

我想知道如何使用ES6的类箭头函数编写以下代码。

class BooksApp extends React.Component {
   constructor(props) {
   super(props);
   this.handleBookChange = this.handleBookChange.bind(this);

听起来这堂课想教你如何理解JavaScript类中的this和scope的用法。 使用React,您还可以执行以下操作:

class BooksApp extends React.Component {
  state = {
    name: this.props.name // sample value
  };

  handleBookChange = event => {
     // do stuff 
     // Arrow functions do not have their own 'this' so a bind is unnecessary. 
     // The 'this' in this method is at the class level.
  };

  render = () => {
    const { name } = this.state;
    return <div>
     <h1>{ name }</h1>
     <button onClick={this.handleBookChange} />
    </div>
  }
}

箭头功能是自我约束力,但它意味着,如果你写一个类中的箭头功能,您并不需要绑定this在类的构造函数和无处不在你需要的功能,它可与this ; 因此您的代码必须像这样:

Class BookApp extends React.Components {
    handleBookChange= () => {
        // your function logic implement here
    }
}

为什么会这样? 箭头函数中的此关键字引用其上下文,即BookApp,这就是我们想要的! 您也可以在不使用类的情况下实现此代码。 您不再需要this

如果您对维护组件的状态不感兴趣,则可以尝试使用这种简单的功能组件

const BookApp = (props) => {
   const handleBookChange = (e) => {
   }

   return (<div>
             Functional Component 
            <button onClick={handleBookChange}></button>
           </div>
          );
}

这个问题看起来有点模棱两可。 但是,我相信很有可能避免使用绑定词。

基本上(我正在使用这种模式和工作方式):

   class BooksApp extends React.Component {
       constructor(props) {
       super(props);
       this.handleBookChange = ( your params ) => {
                           your function code
                     };

如果我的内存可用,要启用此模式,我必须将其包含在webpack中(您的配置文件中可能需要类似的东西):

{ test: /\.jsx?$/, loader: 'babel-loader', include: /ui/, query: { presets: ['es2015', 'stage-0', 'react'] } },

我喜欢这种模式的原因是让我想起-这个词-这是一个属于React类的函数,因为我们可以声明不属于任何类的函数。

暂无
暂无

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

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