react绑定this_React绑定模式:处理“ this”的5种方法
react绑定this
JavaScript’s this keyword behavior has confused developers for ages.
JavaScript的this关键字行为使开发人员困惑了很长时间。
There are at least five ways to handle the this context in React. Let’s consider the merits of each approach.
在React中至少有五种方法来处理这个上下文。 让我们考虑每种方法的优点。
1.使用React.createClass (1. Use React.createClass)
If you use React.createClass, React autobinds all functions to this. So the this keyword is bound to your component’s instance automatically:
如果使用React.createClass , React会将所有函数自动绑定到此 。 因此, 此关键字会自动绑定到组件的实例:
// This magically works with React.createClass// because `this` is bound for you.onChange={this.handleChange}
However, with the advent of ES6 classes, this non-standard approach to creating classes isn’t the future of React. In fact, createClass is likely to be extracted from React core in a future release.
但是,随着ES6类的出现,这种创建类的非标准方法并不是React的未来。 实际上, 在将来的发行版中很可能会从React核心中提取createClass 。
2.绑定渲染 (2. Bind in Render)
The rest of these approaches assume you’re declaring React components via ES6 classes. If you use an ES6 class, React no longer autobinds. One way to resolve this is to call bind in render:
这些方法的其余部分假定您通过ES6类声明React组件。 如果使用ES6类,React将不再自动绑定。 解决此问题的一种方法是在render中调用bind:
onChange={this.handleChange.bind(this)}
This approach is terse and clear, however, there are performance implications since the function is reallocated on every render. This sounds like a big deal, but the performance implications of this approach are unlikely to be noticeable in most apps. So ruling this out at the start for performance reasons is a premature optimization. That said, here’s an example where the performance impact of this approach mattered.
这种方法简洁明了,但是,由于功能会在每个渲染器上重新分配,因此存在性能影响。 这听起来似乎很重要,但是这种方法对性能的影响在大多数应用程序中不太明显。 因此,出于性能原因在一开始就将其排除在外是一项过早的优化。 就是说, 这是此方法对性能的影响至关重要的示例 。
Bottom-line, if you’re experiencing performance issues, avoid using bind or arrow functions in render.
底线是,如果遇到性能问题,请避免在render中使用bind或arrow函数 。
3.在渲染中使用箭头功能 (3. Use Arrow Function in Render)
This approach is similar to #2. You can avoid changing the this context by using an arrow function in render:
此方法类似于#2。 您可以通过在render中使用箭头功能来避免更改此上下文:
onChange={e => this.handleChange(e)}
This approach has the same potential performance impact as #2.
此方法与#2具有相同的潜在性能影响。
The alternative approaches below are worth considering because they offer superior performance for little extra cost.
下面的替代方法值得考虑,因为它们以很少的额外成本提供了卓越的性能。
4.绑定到构造函数 (4. Bind in Constructor)
One way to avoid binding in render is to bind in the constructor (the other approach is discussed in #5 below).
避免在render中绑定的一种方法是在构造函数中绑定(另一种方法将在下面的#5中讨论)。
constructor(props) {super(props);this.handleChange = this.handleChange.bind(this);
}
This is the approach currently recommended in the React docs for “better performance in your application”. This is also the approach I use in “Building Applications with React and Redux in ES6” on Pluralsight.
目前,这是React文档中建议的 “更好的应用程序性能”方法。 这也是我在Pluralsight上的“ 在ES6中使用React和Redux构建应用程序 ”中使用的方法。
However, on most apps the performance implications of approach #2 and #3 won’t be noticeable, so the readability and maintenance advantages of approach #2 and #3 may outweigh performance concerns in many apps.
但是,在大多数应用程序中,方法#2和#3的性能影响不会很明显,因此在许多应用程序中,方法#2和#3的可读性和维护优势可能会超过性能问题。
But if you’re willing to use stage-2 features, the final option below is likely your best bet.
但是,如果您愿意使用第二阶段的功能,那么下面的最后一个选择可能是您最好的选择。
5.在Class属性中使用Arrow函数 (5. Use Arrow Function in Class Property)
This technique relies upon the proposed class property feature. To use this approach, you must enable transform-class-properties or enable stage-2 in Babel.
此技术依赖于建议的类属性功能 。 要使用此方法,必须在Babel中启用transform-class-properties或启用stage-2 。
handleChange = () => {// call this function from render // and this.whatever in here works fine.
};
This approach has multiple advantages:
这种方法具有多个优点:
Arrow functions adopt the this binding of the enclosing scope (in other words, they don’t change the meaning of this), so things just work automatically.
箭头函数采用封闭范围的this绑定 (换句话说,它们不会改变此含义),因此事情会自动进行。
- It avoids the performance issues of approaches #2 and #3.它避免了方法2和方法3的性能问题。
- It avoids the repetition in approach #4.它避免了方法4中的重复。
It’s straightforward to refactor from the ES5 createClass style into this style by converting relevant functions into arrow functions. In fact, there’s a completely automated way to handle this using a codemod.
通过将相关功能转换为箭头功能,可以很容易地将ES5 createClass样式重构为这种样式。 实际上,有一种使用codemod 处理此问题的完全自动化的方法 。
摘要 (Summary)
This flowchart that sums up the decision.
该流程图总结了决策。
Here are full working examples of all 5 approaches:
以下是所有5种方法的完整工作示例:
// Approach 1: Use React.createClass
var HelloWorld = React.createClass({getInitialState() {return { message: 'Hi' };},logMessage() {// this magically works because React.createClass autobinds.console.log(this.state.message);},render() {return (<input type="button" value="Log" onClick={this.logMessage} />);}
});// Approach 2: Bind in Render
class HelloWorld extends React.Component {constructor(props) {super(props);this.state = { message: 'Hi' };}logMessage() {// This works because of the bind in render below.console.log(this.state.message);}render() {return (<input type="button" value="Log" onClick={this.logMessage.bind(this)} />);}
}// Approach 3: Use Arrow Function in Render
class HelloWorld extends React.Component {constructor(props) {super(props);this.state = { message: 'Hi' };}logMessage() {// This works because of the arrow function in render below.console.log(this.state.message);}render() {return (<input type="button" value="Log" onClick={() => this.logMessage()} />);}
}// Approach 4: Bind in Constructor
class HelloWorld extends React.Component {constructor(props) {super(props);this.state = { message: 'Hi' };this.logMessage = this.logMessage.bind(this);}logMessage() {// This works because of the bind in the constructor above.console.log(this.state.message);}render() {return (<input type="button" value="Log" onClick={this.logMessage} />);}
}// Approach 5: Arrow Function in Class Property
class HelloWorld extends React.Component {// Note that state is a property,// so no constructor is needed in this case.state = {message: 'Hi'};logMessage = () => {// This works because arrow funcs adopt the this binding of the enclosing scope.console.log(this.state.message);};render() {return (<input type="button" value="Log" onClick={this.logMessage} />);}
}
So what do people prefer? Here’s the poll:
那么人们喜欢什么呢? 这是民意调查:
Have other ways you handle this? Please chime in via the comments.
您还有其他处理方式吗? 请通过评论加入。
Huge thanks to @dan_abramov, @kentcdodds, and @dmosher for their valuable input and review!
非常感谢@dan_abramov , @kentcdodds和@dmosher的宝贵意见和评论!
Cory House is the author of “Building Applications with React and Redux in ES6”, “Building Applications with React and Flux”, “Clean Code: Writing Code for Humans” and multiple other courses on Pluralsight. He is a Software Architect at VinSolutions, Microsoft MVP, and trains software developers internationally on software practices like front-end development and clean coding.
Cory House是“ 在ES6中使用React和Redux 构建应用程序 ”,“ 使用React和Flux构建应用程序 ”,“ 纯净代码:为人类编写代码 ”以及其他有关Pluralsight的课程的作者。 他是Microsoft MVP VinSolutions的一名软件架构师,并在软件开发方面对国际软件开发人员进行了培训,例如前端开发和简洁编码。
翻译自: https://www.freecodecamp.org/news/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56/
react绑定this
相关文章:

php 文件限速下载代码
<?php include("DBDA.class.php"); $db new DBDA(); $bs $_SERVER["QUERY_STRING"]; //获取由提交界面传过来的参数 $bss substr($bs,3); //截取 后面的值$sql "select video from shangpin where id{$bss}"; //获取视频文件路径 $s…

【Java】Linux下安装配置Oracle JDK 1.7版本
1 环境 Vmware虚拟机中的Ubuntu 12.04 32位系统 2具体安装步骤 ①下载最新的jdk包 注意jdk区分32位版本和64位版本,要与Ubuntu兼容才行 下载地址 http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html ②创建一个目录,…

Swift 换肤方案的实现使用SwiftTheme框架
SwiftTheme 框架进行换肤 本地创建多个plist文件 设置不同图片颜色数组 飞机票 demo Foundationimport SwiftTheme// 创建一个枚举类型进行换肤 enum ChangeTheme:Int {case theme1 0;case theme2 1;case theme3 2;// 创建一个静态方法去换肤 去加载本地的plist文件stati…

linux生日_代码简介:让我们用25个Linux事实来庆祝Linux的25岁生日。
linux生日Here are three stories we published this week that are worth your time:这是我们本周发布的三个值得您关注的故事: Linux is 25. Yay! Let’s celebrate with 25 stunning facts about Linux: 6 minute read Linux是25。是的! 让我们用有关…

网页中;window.onerror=function(){return!0};
在浏览网页的时候发现一段:window.οnerrοrfunction(){return!0}; 于是就顺手点了搜索,发现是被 adsafe关闭了 。 把adsafe退出就能显示了。 转载于:https://www.cnblogs.com/Tiramisu001/p/6136931.html

xib 拖关联控件的时候报Could not insert new outlet connection错误
~/Library/Developer/XCode/DerivedData 目录中删除对应的项目文件 重新打开工程即可

hdu 4901
计数dp 做不出来真是惭愧。。。 #include <cstdio> #include <cstdlib> #include <cmath> #include <stack> #include <vector> #include <sstream> #include <cstring> #include <string> #include <map> #include <…

初创企业股权架构_初创企业如何以每月不到200美元的价格利用生产级基础架构...
初创企业股权架构Before you can launch a new service, you need infrastructure. You want reliability, scalability, and many other -ilities. But you don’t want to break the bank.在启动新服务之前,您需要基础架构。 您需要可靠性,可伸缩性和许…

git review devops过程
自己搭建的devops环境是gitlab/gerrit/jenkins 1. 首先自己checkout一个自己的代码分支,一般不要在master上做直接修改 2. 修改后git add file, git commit 3. git review 4. jenkins自动部署测试 5. 人工review代码,如果可以就提交并merge,…

swift判断iPhone 各种型号
// iPhoneXR let iPhoneXR:Bool __CGSizeEqualToSize(CGSize(width: 828, height: 1792), UIScreen.main.currentMode?.size ?? CGSize(width: 0, height: 0)); // iPhoneX let iPhoneX:Bool __CGSizeEqualToSize(CGSize(width: 1125, height: 2436), UIScreen.main.curr…

轻有力读后感ppt_如果您希望招聘人员认真对待您,请建立强有力的个人叙述。...
轻有力读后感pptby Garreth Dottin通过Garreth Dottin 如果您希望招聘人员认真对待您,请建立强有力的个人叙述。 (If you want recruiters to take you seriously, build a strong personal narrative.) We’ve all been there. Hunched over a desk. Scrolling th…

每天一个linux命令(10):cat 命令
cat命令的用途是连接文件或标准输入并打印。这个命令常用来显示文件内容,或者将几个文件连接起来显示,或者从标准输入读取内容并显示,它常与重定向符号配合使用。 1.命令格式: cat [选项] [文件]... 2.命令…

Swift 中使用Alamofire 免证书的设置
let manager SessionManager.defaultmanager.delegate.sessionDidReceiveChallenge {session,challenge inreturn (URLSession.AuthChallengeDisposition.useCredential,URLCredential(trust:challenge.protectionSpace.serverTrust!))}

“System.Data.OracleClient.OracleConnection”已过时
处理办法: 在oracle 安装目录下 找到 Oracle.DataAccess.dll添加引用,然后 using Oracle.DataAccess.Client;其他的都不用动,即可。连接字符串中 如有 用的是 userxxx 就改成user idxxx把原来 Using 的System.Data.OracleClient去掉即可。 --…

我开发的代码,如何申请版权_代码简介:我花了3个月时间申请开发人员职位。 这是我学到的。...
我开发的代码,如何申请版权Here are three stories we published this week that are worth your time:这是我们本周发布的三个值得您关注的故事: I spent 3 months applying to jobs after a coding bootcamp. Here’s what I learned: 5 minute read 编码训练营结…

Chapter 2 Open Book——29
Which left me with nothing to do but try to not look at him…unsuccessfully. 我没什么事情可以做但是我尝试不去看他,但是失败了。 I glanced up, and he was staring at me, that same inexplicable look of frustration in his eyes. 我瞥了一眼,…

js回调与异步加载的用法
以前还是菜鸟的时候(虽然现在依然很菜 -_-|| )对异步加载与回调函数的技术无比向往,但也一直没有使用过,这次因为页面逻辑太过复杂,一堆请求逻辑,如果还是用顺序请求,页面的速度。。。 领导又要…

Swift 字符串去除换行符空格符
capitalizedLetters:大写controlCharacters:控制符 whitespacesAndNewlines:空格换行 decimalDigits:小数 letters:文字 lowercaseLetters:小写字母 uppercaseLetters:大写字母 nonBaseCharacte…

谈论源码_6,000名自由职业者谈论金钱,幸福和对未来的希望
谈论源码More than 6,000 US-based freelancers responded to a new in-depth survey. I dug through the data and pulled out the most interesting insights, which paint a picture of optimistic professionals who have taken control of their own destiny.超过6,000名美…

第一篇随笔——新的开端
新的开端 这是我第一次开通博客也是第一次在博客上写随笔,这既是博客的新开端也是JAVA学习的新开端,希望能好好经营这第一个博客~。 觉得自己专业吗?对专业的期望 对于这个问题我不得不坦然承认虽然进入信安专业已经有一年的时间了࿰…

快速入门linux系统的iptables防火墙 1 本机与外界的基本通信管理
概述 iptables是一种运行在linux下的防火墙组件,下面的介绍可以快速的学习iptables的入门使用。 特点(重要) 它的工作逻辑分为 链、表、规则三层结构。数据包通过的时候,在对应表中,规则从上向下匹配,匹配到…

iOS 根据数组中的字典的value值进行排序
NSMutableArray *resArr [NSMutableArray array];// 先把所有值的装进一个数组中NSMutableArray *valArr [NSMutableArray array];for (int i 0; i < arr.count; i ) {NSDictionary *dic arr[i];NSString * str [NSString stringWithFormat:"%-%d",dic["…

矢量数编码有哪几种类型_6种最理想的编码工作(以及吸引每个人的类型)
矢量数编码有哪几种类型by David Venturi大卫文图里(David Venturi) 6种最理想的编码工作(以及吸引每个人的类型) (The 6 most desirable coding jobs (and the types of people drawn to each)) Free Code Camp问了15,000个人,他们是谁,以及他们如何学…

sleep和wait到底什么区别
wait是在当前线程持有wait对象锁的情况下,暂时放弃锁,并让出CPU资源,并积极等待其它线程调用同一对象的notify或者notifyAll方法。注意,即使只有一个线程在等待,并且有其它线程调用了notify或者notifyAll方法ÿ…

Swift Code Snippet
1 swi_crecell func numberOfSections(in tableView: UITableView) -> Int {return 1;}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return 5;}// cell高度func tableView(_ tableView: UITableView, heightForRowAt indexPa…

Cocos2d-x lua 编译到Android设备
需要完成Android下ant,ndk,sdk(adt)的环境配置.Java环境配置. 也可以搭建VS下的Lua开发环境. 首先新建项目 cocos new -l lua -d (...address) 然后编译 cocos run -p win32 -s (...address) --ap 19 后面的--ap 19是版本控制. 然后在Eclipse中Import项目,右键项目Build Path添…

c# 数据可视化_#OpenVisConf上的22位数据可视化从业者的10点收获
c# 数据可视化by Siena Duplan通过锡耶纳杜普兰(Siena Duplan) #OpenVisConf上的22位数据可视化从业者的10点收获 (10 Takeaways from 22 Data Visualization Practitioners at #OpenVisConf) Update | May 13, 2016: Videos of all talks are officially live!更新| 2016年5月…

CentOS中Mysql常用操作
安装mysqlyum -y install mysql-server 修改mysql配置vi /etc/my.cnf 这里会有很多需要注意的配置项,后面会有专门的笔记暂时修改一下编码(添加在密码下方): default-character-set utf8设置mysql随系统启动# chkconfig mysqld on ← 设置MySQL服务随系统启动自启动# chkcon…

RXSwift基本使用1
1 cocoapod 安装 import RxSwift import RxCocoa 2 给一个按钮添加点击事件 // 添加点击事件self.rightBtn.rx.tap.subscribe { (event) in}

添加MySql数据库超时设置的相关问题
最近在工作中, 遇到MySql数据库连接超时的问题,申同事帮忙解决了一下,看到原来的MySqlHelper里面没有封装相关的超时方法,就添加了一个,我在这里记录了一下,希望对像我一样入门级的程序员有所帮助ÿ…