我的问题很简单。如果我有一个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绑定到函数上。我正在尝试寻找更好的方法。
this
指向对象实例。箭头函数的定义将使用词法this
,而不是对象的this
。这只是滥用箭头函数。它不仅仅是一种语法快捷方式- 它会以一种不合适的方式改变this
的值,这对于几乎所有方法定义都不合适。当声明方法时,箭头函数根本不是合适的工具。 - jfriend00