1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > react绑定this_React绑定模式:处理“ this”的5种方法

react绑定this_React绑定模式:处理“ this”的5种方法

时间:2020-10-05 20:19:57

相关推荐

react绑定this_React绑定模式:处理“ this”的5种方法

react绑定this

JavaScript’sthiskeyword behavior has confused developers for ages.

JavaScript的this关键字行为使开发人员困惑了很长时间。

There are at least five ways to handle thethiscontext 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 tothis. So thethiskeyword 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, butthe 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 thethiscontext 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 thethisbinding of the enclosing scope (in other words, they don’t change the meaning ofthis),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.createClassvar 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 Renderclass HelloWorld extends ponent {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 Renderclass HelloWorld extends ponent {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 Constructorclass HelloWorld extends ponent {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 Propertyclass HelloWorld extends ponent {// 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 Houseis 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的一名软件架构师,并在软件开发方面对国际软件开发人员进行了培训,例如前端开发和简洁编码。

翻译自: /news/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56/

react绑定this

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。