首页 > 解决方案 > 关键字 this 的值

问题描述

看看下面的代码:

class App extends React.Component {


  go(){
    console.log("Hello",this);
  }
  render() {
    console.log("Hey",this);

    return ( 
      <button onClick={this.go}>Add profile</button>
    );
  } 
}

为什么thisinside的值go是未定义的?thisinsiderender是一个App实例,因为我们调用inside 方法this.go的值应该等于同一个实例。thisgoApp

标签: javascriptreactjs

解决方案


您需要绑定go或使用箭头功能:

export default class App extends React.Component {
  go = () => {
    console.log('Hello', this);
  };
  render() {
    console.log('Hey', this);

    return <button onClick={this.go}>Add profile</button>;
  }
}

推荐阅读