react的事件处理为什么要bind this 改变this的指向?
react的事件处理会丢失this,所以需要绑定,为什么会丢失this?
首先来看摘自官方的一句话:
You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default.
这句话大概意思就是,你要小心jax回调函数里面的this,class方法默认是不会绑定它的
让我十分疑惑,在我的知识范围理解中,class是es6里面新增的方法,不就用来继承原有对象上的属性和方法创建新的对象吗?就是代替原来的构造函数的一种更清晰的方式,为什么就不会绑定this呢?
可是查阅了一些es6的文档,并不是这样的啊,和class方法没啥关系吧,为什么要它背锅呢?
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}> //这里调用的this也能拿到啊??
{this.state.isToggleOn ? 'ON' : 'OFF'} //这里的this为什么没问题?
</button>
);
}
}
这是官网上的一段代码,如果是是因为class的关系,handleClick里面拿不到this,那为什么render里面能拿到this,所以和class根本没关系吧本来就能拿到,那问题出现在哪里,为什么拿不到?
先看看解决办法
第一种,在constructor里面用bind绑定this
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
第二种,声明方法的时候使用箭头函数
handleClick = () => {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
第三种,调用的时候使用箭头函数
render() {
return (
<button onClick={ () => { this.handleClick } }>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
这个时候我想起了原生dom绑定click的方法
<button onclick ="handleClick()">点我</button>
两者比较,我发现了个区别,原生的绑定方法事件名后面多了个()
于是我尝试着在react里面的事件加一个()
render() {
return (
<button onClick={ this.handleClick() }>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
class App extends Component {
handleClick(){
console.log(this); //下面调用加了(),这个时候发现,this是可以拿到的
}
render() {
return (
<div className="App">
<button onClick={this.handleClick()}>点我</button> //这里加了括号的
</div>
);
}
}
好像问题越来越明朗了,为啥会拿不到,和class没有关系,完全是因为react自己封装的东西,先会把{}里面的代码解析一遍,于是大概就是下面这种情况了
const obj = {
num:1
}
obj.handleClick = function () {
console.log(this);
}
console.log(eval(obj.handleClick )); // f(){ console.log(this) } react对{}的解析
(eval(obj.handleClick))() //onclick触发点击事件 这里输出this是window,所以就等于丢失了this指向
console.log(eval(() => { obj.handleClick() })); // () => { obj.handleClick() } react对{}的解析
(eval(() => {obj.handleClick()}))() //onclick触发点击事件 这里输出this还是obj,所以this就保留了
所以问题出在react对{}的解析会把this的指向解除了
react的事件处理为什么要bind this 改变this的指向?的更多相关文章
- React中的事件处理为什么要bind this?
个人总结: 问: 请给我讲一下React中的事件处理为什么要bind this? 答: 好的,比如说我写了一个类组件,有个onClick属性 ,onClick={ this.fun },如果不bind ...
- bind改变this的指向
<script type="text/javascript"> var Hello = function(){ this.setT = function(){ wind ...
- this指向详解及改变它的指向的方法
一.this指向详解(彻底理解js中this的指向,不必硬背) 首先必须要说的是,this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是 ...
- 改变this的指向问题;
用call()和apply()改变this的指向,那什么时候用this呢?(构造函数),那为什么要用构造函数呢?(为了生成对象). 1.解决函数内this指向的问题 (1)var that/_this ...
- JavaScript中this的用法 及 如何改变this的指向
要懂得JavaScript中this的用法,首先需要知道,JavaScript中的作用域相关知识. var fun = function(){ var flag = 1; console.log(fl ...
- 有关call和apply、bind的区别及this指向问题
call和apply都是解决this指向问题的方法,唯一的区别是apply传入的参数除了其指定的this对象之外的参数是一个数组,数组中的值会作为参数按照顺序传入到this指定的对象中. bind是解 ...
- 3种方法改变this的指向
<body> <div style="width: 200px;height: 200px;hotpink;"></div> & ...
- React事件处理函数的bind复用和name复用
一.bind复用 <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset=&qu ...
- react篇章-事件处理
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title&g ...
随机推荐
- The happy secret to better work,https://www.ted.com/talks/shawn_achor_the_happy_secret_to_better_work/transcript#t-100352
When I was seven years old and my sister was just five years old, we were playing on top of a bunk b ...
- Codeforces Round #606 (Div. 2) D - Let's Play the Words?(贪心+map)
- ESA2GJK1DH1K基础篇: Android实现SmartConfig简单Demo
下载源码去 百度安信可 导入源码 等待加载完 我的提示更新下软件 ,我就更新下 安装完成以后重新导入工程 安装到手机 注意,由于Android 9.0 以后的获取WIFI名称需要打开GPS,所以如果提 ...
- 踩iviewui中Tabs 标签页数据绑定坑
今天小颖要实现点击Tabs 标签页中每个标签,并动态获取当前点击的标签值. 一句话说不清楚,那就看动态图吧 小颖一开始看官网写的代码是: <template> <Tabs :valu ...
- python3 pathlib库中的Path类的使用
调用库 from pathlib import Path 获取 Path 的文件名 Path.name 参考 https://blog.csdn.net/amanfromearth/article/d ...
- spring学习-ApplicationContext-spring上下文深入理解
4月份开始复习一遍spring相关知识.让自己巩固一下spring大法的深奥益处,所以就看了大佬的博客,转载留下来日后继续研读.认为重点的标记为红色 以下文章内容转载自:http://www.cnbl ...
- bat无线热点设置
netsh wlan set hostednetwork mode=allow ssid=happyla key=1234567890netsh wlan start hostednetwork
- 面向对象的理解 抽象类&接口
一.关于面向对象 1.什么是面向对象 在解释面向对象之前,先说说面向过程.学过C的同学都知道,C就是面向过程的一种语言.那什么是面向过程呢?比方说组装主机,对于面向过程,需要从0开始.买cpu ...
- CentOS环境设置Hbase自启动
1.在/etc/init.d/目录创建hbase文件 #!/bin/bash # chkconfig: #export JAVA_HOME=/usr/local/jdk1.8.0_191 HBASE_ ...
- ThinkPHP5 使用 JWT 进行加密
使用 Github 的 firebase\JWT - 使用 Composer 安装此扩展 - 代码示例 <?php /** * [InterCommon-接口公用] * @Author Rain ...