简体   繁体   中英

What does React's bind do in this situation?

I am learning React with Hooks, and I don't understand this code:

onAdd={cartITemAddHandler.bind(null, item)}

I understand how this.bind worked somewhat when I learned React years ago. Calling asdf.bind(null, ...) doesn't make any sense to me; that is binding to null. Now I have forgotten and don't understand what bind is doing, especially in the modernized hooks example I am trying to follow.

bind 's purpose is to create a copy of a function which has some of its parameters locked in. The most common case is to lock in the value of this , but it can also be used to lock in regular arguments, and that's what's being done here.

cartITemAddHandler.bind(null, item) creates a copy of cartITemAddHandler , which will receive item as its first argument. It also receives null for this , but the person who wrote this code probably doesn't care what this is, they just need to pass something for bind's first argument, so they can pass what they really care about in the second argument.

PS: bind is not special to React, it's part of the core javascript language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM