Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use bind in React components

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to use bind in React components". In daily operation, I believe many people have doubts about how to use bind in React components. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use bind in React components". Next, please follow the editor to study!

When dealing with onClick-like event binding in React components, you need to explicitly bind the processor context (context), which once made the code redundant and ugly.

Class App extends Component {constructor () {super (); this.state = {isChecked: false};} render () {return (check me:);} toggleCheck () {this.setState (currentState = > {return {isChecked:! currentState.isChecked};});}}

Put a checkbox element on the page, click and switch its selected status. This is an intuitive piece of code, but it doesn't work as well as you think.

Event handler context lost error report

Because the setState method of the React component cannot be found in the onChange event handler of checkbox, it means that the context in which it executes is not the component, but something else. Let's debug it.

Debug to see the value of this after losing context

Unexpectedly, it's undefined, which is executed in a completely wild environment without any context.

WHY

Of course, this is not React's pot, this is how this works in JavaScript. For more information, see Chapter 2: this All Makes Sense Now! To trace the underlying reason, simply put, the value of this depends on how the function is called.

Default binding

Function display () {console.log (this)}

Display () / / Global `window` in strict mode and `undefined` in non-strict mode

Implicit binding

Called through an object, the context of the function is implicitly specified as the object.

Var obj = {name: 'Nobody', display: function () {console.log (this.name);}}; obj.display (); / / Nobody. What is taken in it is the `name` attribute of obj

However, if you assign a method on this object to another variable, or in the form of a parameter, and then execute it, the situation will be different.

Var obj = {name: "Nobody", display: function () {console.log (this.name);}}; var name = "global!"; var outerDisplay = obj.display;outerDisplay (); / / global! The `name` obtained here is the inner one in the global.

Here, assigning a value to outerDisplay and then calling it is equivalent to calling an ordinary function, not the one in the object, so this is a global object, and there happens to be a name variable defined in the global. Similarly, if you are in strict mode, the so-called undefiend.name will not be accessed because this is undefined at this time, so an error will be thrown.

Function invoker (fn) {fn ();} setTimeout (obj.display, 1000); / / global invoker (obj.display); / / global!

When setTimeout is called here, because its signature is actually setTimeout (fn,delay), it can be understood that obj.display is assigned to its input parameter fn, which actually executes the fn instead of the method on the object. The same is true for the invoker function.

Force binding

At this point, bind becomes the hero who saves the world, and we can use it to explicitly specify the execution context of the function at any time.

Var name = "global!"; obj.display = obj.display.bind (obj); var outerDisplay = obj.display;outerDisplay (); / / Nobody

Bind binds the specified context to the function and returns a new function. The new function will not affect its context by assigning values or passing parameters. It will always be the one we specified when it is executed.

On-site reduction

With the above background, you can restore the problem at the beginning of the article, that is, the context loss of the event handler.

The HTML tag in JSX essentially corresponds to a function in React that creates the tag. For example, the div compiler you write will actually be React.createElement ('div'). So when you write, you actually call React.createElement to create a tag.

React.createElement (type, [props], [... children])

The attributes on the tag are passed to the createElement function as props arguments.

Indicates that the toggleCheck method in the component is assigned to the input parameter props of createElement (props is an object that receives all attributes written on the tag,). The actual call, as mentioned above, is no longer the toggleCheck method in the component.

React.createElement (type, props) {/ / Let's create one and call `props.onChange` when the value of Props.onChange () / / it is no longer the original method, and the context is lost.}

Because ES6's Class is executed in strict mode, if this is used in the event handler, it is undefined.

So it's not surprising that you see the official example of React that has a bind (this) statement in constructor to correct the skewed execution context of the event handler.

Constructor () {super (); this.state = {isChecked: false}; + this.toggleCheck = this.toggleCheck.bind (this);}

This works, but the existence of this code is really awkward, because

It makes no sense to the business, it only increases the amount of code.

It's ugly. Every time you add a processor, you have to add such a binding.

Redundancy, such repetitive code has a lot of redundancy in the project, confusing the original method in the search

There are many ways to avoid it, depending on which one tastes best. Let's take a look at how to avoid writing these binding methods.

# 0 bindings within the line

The easiest thing to do is to bind within a line so that you don't have to write a separate sentence.

# 1 Arrow function

Because the arrow function does not create a new scope, its context is a lexically context. So when binding event handlers, directly using the haircut function is a convenient way to avoid it.

This.toggleCheck ()} / >

# 2 change the method of a class to an attribute

If you use this handler as a property of the component, this property exists as the event handler in the form of an arrow function, and the context can be obtained normally when executed.

-toggleCheck () {+ toggleCheck = () > {this.setState (currentState = > {return {isChecked:! currentState.isChecked};});} at this point, the study on "how to use bind in React components" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report