React 学习---组件自定义方法中的 this 值为 undefined,如何解决?

137 阅读1分钟

组件自定义方法中的 this 值为 undefined,如何解决?

  • 赋值语句+箭头函数(推荐写法)
  • 在构造器中通过 bind() 强制绑定 this(写法繁琐)
  • 绑定回调函数时使用箭头函数(某些情况存在性能问题)

1. 赋值语句+箭头函数(推荐写法)

test 方法内的 this 值成功绑定到 Game 组件实例对象上

(伪代码...)
class Game extends React.Component {

 test = () => {
     console.log(this,'this')
 }      
 
 render() {
    return (
      <div>
        <h1 onClick={this.test}>JSX 回调函数中的 this 问题</h1>
      </div>
    );
  }
}

// 
ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

2. 在构造器中通过 bind() 强制绑定 this(写法繁琐)

test 方法内的 this 值成功绑定到 Game 组件实例对象上

(伪代码...)
class Game extends React.Component {

 constructor(props){
     super(props)
     this.test = this.test.bind(this)
 }    
 
 test(){
     console.log(this,'this')
 }   
 
 render() {
    return (
      <div>
        <h1 onClick={this.test}>JSX 回调函数中的 this 问题</h1>
      </div>
    );
  }
}

// 
ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

3. 绑定回调函数时使用箭头函数(某些情况存在性能问题)

据官方文档所说,在大多数情况下,这没什么问题,但如果该回调函数作为 prop 传入子组件时,这些组件可能会进行额外的重新渲染。我们通常建议在构造器中绑定或使用 class fields 语法来避免这类性能问题。

(伪代码...)
class Game extends React.Component {

 test() {
     console.log(this,'this')
 }      
 
 render() {
    return (
      <div>
        <h1 onClick={() => this.test()}>JSX 回调函数中的 this 问题</h1>
      </div>
    );
  }
}

// 
ReactDOM.render(
  <Game />,
  document.getElementById('root')
);