首先,让我们从每种技术的示例开始!
但是区别更多地与JavaScript语言本身有关。
绑定:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler() {
console.log( this )
}
render() {
return <button onClick={this.clickHandler}>Click Me</button>
}
}
箭头函数:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props)
}
clickHandler = () => {
console.log( this )
}
render() {
return <button onClick={this.clickHandler}>Click Me</button>
}
}
优缺点:
在公共类字段上使用箭头函数更易读,因为代码行数较少,
但请记住,使用箭头函数可能会影响三件事:
首先是内存和性能;当您使用类字段定义函数时,整个方法驻留在每个类的实例上,而不是原型上,但使用bind技术,只有一个小的callback
存储在每个实例上,调用存储在原型上的方法。
第二个可能受到影响的是您编写单元测试的方式。
您将无法使用组件原型来存根函数调用,如下所示:
const spy = jest.spyOn(MyComponent.prototype, 'clickHandler');
expect(spy).toHaveBeenCalled();
要想存根该方法,必须找到另一种方法,例如通过在props
中传递虚拟回调函数或检查state
更改。
最后是性能问题;
取决于您的脚本运行的JavaScript
引擎,
使用超过某个限制的内存可能导致几乎随机的运行时挂起
(也称逻辑操作的延迟),
即使系统尚未低于内存,但除此之外,逻辑的运行时性能对于两种技术应该是相同的。
请参见下面“其他工具”部分以获取解决方法。
结论
计算机非常擅长阅读代码;您不必担心。
您可以考虑使用类属性箭头函数使您的代码更易于阅读。
其他工具:
如果您想保持人类可读性和性能,请考虑使用plugin-transform-arrow-functions插件,只需运行npm i --save-dev @babel/plugin-transform-arrow-functions
并将其添加到您的"babel.config.js
"或".babelrc
"文件中,例如:
{
"presets": ["module:metro-react-native-babel-preset"],
"plugins": [
["@babel/plugin-proposal-decorators", { "decoratorsBeforeExport": false }],
["@babel/plugin-transform-arrow-functions", { "spec": true }]
]
}
"spec": true
表示插件会自动将箭头函数转换为方法/函数绑定(位于 prototype
中)。
此外,似乎该插件不与 React Native 兼容(至少在链接帖子中提到的版本中)。
或者,您可以使用类似 auto-bind 装饰器 的东西,将上面的示例转换为:
import React from 'react';
import { boundMethod as bind } from 'autobind-decorator';
class MyComponent extends React.Component {
constructor(props) {
super(props)
}
@bind
clickHandler() {
console.log( this )
}
render() {
return <button onClick={this.clickHandler}>Click Me</button>
}
}
请注意,不需要在每个函数上都放置
@bind
。您只需要绑定传递的函数。例如:
onClick={this.doSomething}
或者
fetch.then(this.handleDone)
。
this
。这是我能想到的两者之间的一个区别。 - Pat Mellon() => {this.clickEvent()}
- Yury Tarabanko