首页 > 解决方案 > 为什么我的类方法可以在 React 中工作而没有显式地将它绑定到“this”?

问题描述

我束手无策,有人能告诉我为什么这行得通,即使我注释掉了对“this”的显式绑定吗?据我了解,如果没有明确绑定到类,则“this”应该是未定义的,因此这个例子应该给我一个错误,但它确实有效。我错过了什么?

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 1
    };

    // this.handleAdd = this.handleAdd.bind(this);
    // this.handleAdd = this.handleSub.bind(this);
  }

  handleAdd() {
    this.setState(prevState => ({ count: prevState.count + 1 }));
  }
  
  handleSub() {
    this.setState(prevState => ({ count: prevState.count - 1 }));
  }

  render() {
    return (
      <div>
        <h1>Counter is at {this.state.count}</h1>
        <button onClick={() => this.handleAdd()}>+</button>
        <button onClick={() => this.handleSub()}>-</button>
      </div>
    )
  }
}

export default Counter;

标签: reactjsthis

解决方案


这是因为您正在使用箭头函数来调用您的方法。箭头函数this绑定到最近的非箭头父函数中的值。


推荐阅读