React类组件this问题

 1 class App extends React.Component {
 2   constructor() {
 3     super();
 4     this.state = {
 5       message: 'hello react'
 6     }
 7   }
 8   myFn() {
 9     console.log(this); // undefined
10   }
11   render() {
12     return (
13       <div>
14         <div>{this.state.message}</div>
15         <button onClick={this.myFn}>按钮</button>
16       </div>
17     )
18   }
19 }

无法拿到 this 的原因是这个点击事件是React通过 apply 来调用的,在调用的时候修改了 myFn 函数的 this 为 undefined 

 

解决方案

将 myFn 修改为箭头函数

1 myFn = () => {
2     console.log(this); // App{ state:{message:'hello react'}, myFn:f, ...}
3   }
  • 箭头函数不会创建自己的 this ,只会从自己的作用域链的上一层继承this 

将点击事件的函数修改为箭头函数可以解决 this 是 undefined 的情况,但没有解决传递参数的问题。

我们需要在定义点击事件的时候使用一个箭头函数,在这个箭头函数体里面去调用 myFn 方法,就可以解决传递参数的问题

 1 class App extends React.Component {
 2   constructor() {
 3     super();
 4     this.state = {
 5       message: 'hello react'
 6     }
 7   }
 8   myFn = (num) => {
 9     console.log(num); // 66
10   }
11   render() {
12     return (
13       <div>
14         <div>{this.state.message}</div>
15         <button onClick={() => this.myFn(66)}>按钮</button>
16       </div>
17     )
18   }
19 }

这样可以在触发 myFn 函数时,传递参数。

事件对象

在触发事件时,会自动传递一个 react 包装过的事件对象给我们使用

 1 class App extends React.Component {
 2   constructor() {
 3     super();
 4     this.state = {
 5       message: 'hello react'
 6     }
 7   }
 8   myFn = (e) => {
 9     console.log(e);
10   }
11   render() {
12     return (
13       <div>
14         <div>{this.state.message}</div>
15         <button onClick={(event) => this.myFn(event)}>按钮</button>
16       </div>
17     )
18   }
19 }

 

posted @ 2021-10-24 14:16  霸哥yyds  阅读(368)  评论(0)    收藏  举报