为什么箭头函数可以用在 ReactJS classes 而不能用在纯 ES6 class 上?
Why arrow functions can be used on ReactJS classes but not on a pure ES6 class?
我想知道我是否可以使用箭头函数编写纯 ES6 class。这是我的 class 示例:
class PhoneNumber {
constructor(phoneNumber) {
this.phoneNumber = phoneNumber;
}
testEmpty() {
if (!this.phoneNumber) return true;
return false;
}
}
好像不能这样写:
class PhoneNumber {
constructor = phoneNumber => {
this.phoneNumber = phoneNumber;
}
testEmpty = () => {
if (!this.phoneNumber) return true;
return false;
}
}
尽管我可以在 React 上写类似的东西:
class PhoneNumber extends React.Component {
state = {
phoneNumber: this.props.phoneNumber;
}
testEmpty = () {
if (!this.state.phoneNumber) return true;
return false;
}
}
为什么 React 组件,即使是 class,也接受 ES6 箭头函数而我的纯 class 不接受?
构造函数根本不能是箭头函数。
您可以在 React 中创建箭头方法,因为 React 在底层使用 class 字段的提案。你可以使用 babel 提案插件将它们添加到你的项目中。
使用箭头 class 方法的好处是 this 在这种方法中的值将在回调中引用 class 本身。因此,您可以在没有包装函数或没有 bind() 的情况下在事件侦听器中使用箭头方法。
我想知道我是否可以使用箭头函数编写纯 ES6 class。这是我的 class 示例:
class PhoneNumber {
constructor(phoneNumber) {
this.phoneNumber = phoneNumber;
}
testEmpty() {
if (!this.phoneNumber) return true;
return false;
}
}
好像不能这样写:
class PhoneNumber {
constructor = phoneNumber => {
this.phoneNumber = phoneNumber;
}
testEmpty = () => {
if (!this.phoneNumber) return true;
return false;
}
}
尽管我可以在 React 上写类似的东西:
class PhoneNumber extends React.Component {
state = {
phoneNumber: this.props.phoneNumber;
}
testEmpty = () {
if (!this.state.phoneNumber) return true;
return false;
}
}
为什么 React 组件,即使是 class,也接受 ES6 箭头函数而我的纯 class 不接受?
构造函数根本不能是箭头函数。 您可以在 React 中创建箭头方法,因为 React 在底层使用 class 字段的提案。你可以使用 babel 提案插件将它们添加到你的项目中。 使用箭头 class 方法的好处是 this 在这种方法中的值将在回调中引用 class 本身。因此,您可以在没有包装函数或没有 bind() 的情况下在事件侦听器中使用箭头方法。