【发布时间】:2017-10-20 05:25:41
【问题描述】:
我的问题很简单。如果我在 ES6 中有一个类,是否可以在其中使用箭头函数?
import React, { Component } from 'react';
export default class SearchForm extends Component {
state = {
searchText: ''
}
onSearchChange = e => {
this.setState({ searchText: e.target.value });
}
handleSubmit = e => {
e.preventDefault();
this.props.onSearch(this.query.value);
e.currentTarget.reset();
}
render() {
return (
<form className="search-form" onSubmit={this.handleSubmit} >
<label className="is-hidden" htmlFor="search">Search</label>
<input type="search"
onChange={this.onSearchChange}
name="search"
ref={(input) => this.query = input}
placeholder="Search..." />
<button type="submit" id="submit" className="search-button">
<i className="material-icons icn-search">search</i>
</button>
</form>
);
}
}
我问的原因是我的控制台出现错误,即使使用 Babel 也是如此。互联网上似乎有很多资源表明您可以做到这一点(其中大部分是关于使用 React 开发的)。
这是 Babel 应该做的事情,并且最终会得到原生支持吗?
我得到的错误是一个意外的 = 符号,就在括号之前。
编辑:我忘了说,我希望这样做的原因是在类的上下文中使用 this 关键字。如果我使用常规函数 - 据我了解 - 我必须将 this 绑定到该函数。我正在尝试寻找一种更好的方法来做到这一点。
【问题讨论】:
-
不,事情不是这样运作的。正确的做法是 sample 提供的 constructor() {}。
-
只是出于好奇,您为什么要这样做?有什么好处?
-
使用 React 开发并希望在不显式绑定的情况下使用 this 关键字。
-
另见stackoverflow.com/questions/31362292/… - 可能重复的问题
-
不要将箭头函数用于您希望
this指向对象实例的方法。箭头函数定义将使用词法this,而不是对象this。这只是对箭头功能的滥用。它不仅仅是一种语法快捷方式——它以一种几乎不适合所有方法定义的方式更改了this的值。声明方法时,箭头函数只是工作的错误工具。
标签: javascript class ecmascript-6 arrow-functions