好程序员分享 React-010- 事件处理函数的 this 指向问题 , 区分普通函数与事件处理函数
1 、 普通函数是直接调用的。不存在 this 指向问题,谁调用的, this 指向就是谁。
2 、 普通函数没有事件对象 event
3 、 事件处理函数其实也是一个函数,只是他绑定在某个事件上。
4 、 事件处理函数的 this 默认指向 undefined
解决 this指向问题的4种办法
1 、 直接在事件绑定的地方加上 .bind(this)
< button onClick = { this .handleClick.bind( this )} > 点我 < /button>
2 、 使用箭头函数
< button
onClick = { event => {
this .handleClick(event);
}}
>
点我
< /button>
3 、 在构造函数中统一进行 this 指向的绑定
constructor() {
super ();
this . handleClick = this . handleClick . bind ( this );
}
render() {
return (
< button onClick = { this .handleClick} > 点我 < /button>
)
}
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
< Child onFn1 = { this .handleFn1.bind( this )} />
// 由于 .bind() 方法每次都会返回一个新的函数,所以这种方式不推荐。。。。
< Child onFn1 = {() => { this . handleFn1 () }} />
// 由于 每次执行到这行代码,箭头返回都是一个新的箭头函数,所以这种方式不推荐
constructor() {
super ();
this . handleFn1 = this . handleFn1 . bind ( this )
}
< Child onFn1 = { this .handleFn1} />
// 由于 constructor 构造函数只会执行一次,后续执行到 Child 的代码,传递过去的 onFn1 没有发生变化
// 所以这种方式推荐
< Child onFn1 = { this .handleFn1} />
handleFn1 = () => {
...
}
// 这种方式同样也推荐。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69913892/viewspace-2653206/ ,如需转载,请注明出处,否则将追究法律责任。