如何使用箭头函数(public class fields)作为类方法? [英] How to use arrow functions (public class fields) as class methods?

查看:1972
本文介绍了如何使用箭头函数(public class fields)作为类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢在React中使用ES6类,以前我将我的方法绑定到当前对象(在第一个例子中显示),但ES6允许我永久地将一个类函数绑定到一个类实例中? (当作为回调函数传递时有用)当我尝试使用CoffeeScript时,我收到错误:

  class SomeClass扩展了React.Component {

//而不是这个
构造函数(){
this.handleInputChange = this.handleInputChange.bind(this)
}

//可以这样做吗?我只是得到语法错误?
handleInputChange(val)=> {
console.log('selectionMade:',val);
}

所以如果我要通过 SomeClass.handleInputChange ,例如 setTimeout ,它将作用于类实例,而不是窗口

解决方案

您的语法略有偏离,只是在属性名称后面缺少一个等号。

  class SomeClass extends React.Component {
handleInputChange =(val)=> {
console.log('selectionMade:',val);
}
}

这是一个实验性功能。您需要启用Babel中的实验功能才能编译。 这里是实验启用的演示。



要在babel中使用实验功能,您可以从此处。对于此特定功能,您需要 transform-class-properties 插件

  {
plugins:[
transform-class-properties
]
}

您可以阅读更多关于类字段和静态属性的建议 here





I'm new to using ES6 classes with React, previously I've been binding my methods to the current object (show in first example), but does ES6 allow me to permanently bind a class function to a class instance with arrows? (Useful when passing as a callback function.) I get errors when I try to use them as you can with CoffeeScript:

class SomeClass extends React.Component {

  // Instead of this
  constructor(){
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  // Can I somehow do this? Am i just getting the syntax wrong?
  handleInputChange (val) => {
    console.log('selectionMade: ', val);
  }

So that if I were to pass SomeClass.handleInputChange to, for instance setTimeout, it would be scoped to the class instance, and not the window object.

解决方案

Your syntax is slightly off, just missing an equals sign after the property name.

class SomeClass extends React.Component {
  handleInputChange = (val) => {
    console.log('selectionMade: ', val);
  }
}

This is an experimental feature. You will need to enable experimental features in Babel to get this to compile. Here is a demo with experimental enabled.

To use experimental features in babel you can install the relevant plugin from here. For this specific feature, you need the transform-class-properties plugin:

{
  "plugins": [
    "transform-class-properties"
  ]
}

You can read more about the proposal for Class Fields and Static Properties here


这篇关于如何使用箭头函数(public class fields)作为类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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