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 }

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐