React 前端 010 事件处理函数的this指向问题
区分普通函数与事件处理函数 1. 普通函数是直接调用的。不存在 this 指向问题,谁调用的,this 指向就是谁。 2. 普通函数没有事件对象 event 3. 事件处理函数其实也是一个函数,只是他绑定在某个事件上。 4. 事件处理函数的 this 默认指向 undefined 解决this指向问题的4种办法 1. 直接在事件绑定的地方加上 .bind(this) 2. 使用箭头函数 3. 在构造函数中统一进行this指向的绑定 constructor() { super(); this.handleClick = this.handleClick.bind(this); } render() { return ( ) } 4. 使用实验性质的 public class fileds 语法。要去使用的话,的需要babel插件的支持. 1. 安装 @babel/plugin-proposal-class-properties babel 插件 2. 去 babel 的配置文件中,配置好 3. 从新启动项目 class App extends React.Component { handleClick = () => { console.log(this); }; } 为啥要使用 bind 来修改this指向,而不能使用 apply、call? 因为 apply 与 call 他们会直接执行函数,而 bind 会返回一个新的函数。 在调用子组件的时候,需要传递一个方法下去,这时这个方法的this绑定推荐使用哪几种: 推荐使用:在构造函数中的bind 与 public class fileds 语法。 1. 首先要知道的是,父组件render,子组件一定会render 2. 我们希望如果子组件没有发生变化,那么在 父组件render的时候,让子组件不做render。节省性能。 3. 要实现第2点,可以让子组件继承的是 PureComponent 4. PureComponent 。它会帮助我们计算子组件接收到的porps 有没有发生变化,如果有那么就 render .如果没有就阻止render // 由于 .bind() 方法每次都会返回一个新的函数,所以这种方式不推荐。。。。 // 由于 每次执行到这行代码,箭头返回都是一个新的箭头函数,所以这种方式不推荐 constructor() { super(); this.handleFn1 = this.handleFn1.bind(this) } // 由于 constructor 构造函数只会执行一次,后续执行到 Child 的代码,传递过去的 onFn1 没有发生变化 // 所以这种方式推荐 handleFn1 = () => { ... } // 这种方式同样也推荐。