除了在构造函数中绑定this,还有其它方式吗?
在 React(尤其是类组件)中,“如何绑定 this” 是常见的坑点。
除了在构造函数里用 bind,还有几种替代方式,方案如下
1. 构造函数中绑定(传统方式)
class Demo extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.handleClick = this.handleClick.bind(this); // ✅ 传统方式
}
handleClick() {
console.log(this.state.count);
}
render() {
return <button onClick={this.handleClick}>Click</button>;
}
}
优点:性能好(绑定只发生一次)
缺点:写法繁琐,每个方法都要 bind
2. 使用箭头函数定义方法(推荐)
class Demo extends React.Component {
state = { count: 0 };
handleClick = () => {
console.log(this.state.count);
};
render() {
return <button onClick={this.handleClick}>Click</button>;
}
}
说明:
-
箭头函数会自动绑定外层 this(即组件实例);
-
不需要在构造函数里写 bind;
-
是 React 官方推荐的方式之一。
优点:语法简洁,天然绑定 this
缺点:每个实例都会生成新的函数(微小性能差距,但通常可以忽略)
3. 直接在 JSX 中使用箭头函数
class Demo extends React.Component {
state = { count: 0 };
handleClick() {
console.log(this.state.count);
}
render() {
return <button onClick={() => this.handleClick()}>Click</button>;
}
}
优点:最简洁,不需要 bind
缺点:
-
每次 render 都会创建一个新的函数;
-
如果组件频繁渲染,会有轻微性能问题;
-
不推荐在高频更新的列表项中使用。
4. 使用类字段 + 箭头函数结合
class Demo extends React.Component {
handleClick = () => {
console.log(this);
};
}
等价于:
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
React 在编译时(Babel)会自动处理箭头函数绑定。
5. 使用装饰器(较少见)
import autobind from 'autobind-decorator';
class Demo extends React.Component {
@autobind
handleClick() {
console.log(this);
}
render() {
return <button onClick={this.handleClick}>Click</button>;
}
}
优点:优雅,省去大量 bind
缺点:需要 Babel 插件(生产项目中一般不推荐)
总结对比
| 方式 | 是否自动绑定 | 性能 | 写法简洁度 | 推荐度 |
|---|---|---|---|---|
| 构造函数 bind | ✅ 一次 | ✅ 高 | ❌ 繁琐 | ⭐⭐⭐ |
| 箭头函数定义方法 | ✅ 自动 | ✅ 很好 | ✅ 简洁 | ⭐⭐⭐⭐ |
| JSX 内箭头函数 | ✅ 自动 | ⚠️ 每次 render 重新创建 | ✅ 简洁 | ⭐⭐ |
| 装饰器 autobind | ✅ 自动 | ✅ 高 | ✅ 优雅 | ⭐⭐(需 Babel) |
现代 React 写法(尤其在 TypeScript 项目中)
推荐使用 箭头函数定义类方法:
handleClick = () => { ... }
浙公网安备 33010602011771号