React Native bind函数 bind(this)

项目中我们经常会遇到如下写法

bind(this)
//列表显示控件
 renderItem={this.renderUserItem.bind(this)}

那么对于一个函数的调用我们到底什么时候需要.bind(this),什么时候不需要.bind(this)呢?

先说结论:

bind(this)主要出现在函数调用的调用后执行场景中,且主要面向普通函数

并且强烈推荐在该情况下直接bind(this),因为该函数就是绑定作用,

通过该绑定函数的指向就发生了变化(因为普通函数的指向是不固定的,这个操作有点类似箭头函数固定this指向的意思),

自然而然,既然绑定,那么就是调用后执行场景

笼统而言两个作用

1、固定this指向(绑定)

2、调用后执行(不会一进页面就立即渲染)

bind是什么?

/**
     * For a given function, creates a bound function that has the same body as the original function.
     * The this object of the bound function is associated with the specified object, and has the specified initial parameters.
     * @param thisArg The object to be used as the this object.
     * @param args Arguments to bind to the parameters of the function.
     */
    bind<T>(this: T, thisArg: ThisParameterType<T>): OmitThisParameter<T>;
    bind<T, A0, A extends any[], R>(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R;
    bind<T, A0, A1, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R;
    bind<T, A0, A1, A2, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R;
    bind<T, A0, A1, A2, A3, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R;
    bind<T, AX, R>(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R;

/**

*对于给定函数,创建与原始函数具有相同主体的绑定函数。

*绑定函数的this对象与指定的对象关联,并具有指定的初始参数。

*@param thisArg要用作此对象的参数的对象。

*@param args用于绑定函数参数的参数。

*/

从上我们可以看出bind函数其实是一个绑定作用

 就是将一个操作绑定到另一操作上,即一个函数绑定到另一函数,一个指针绑定到另一个指针

那么这个场景就是主要出现在函数调用的 调用后执行操作中

详情参考:React Native 函数的调用

 bind方法的作用也是这样,为指定的事件添加相应的处理函数。就是将处理函数和指定的操作绑定在一起。操作触发时函数执行

备注:

1、如果普通函数出现以下错误TypeError: this.showStr is not a function 那就是没有bind(this)的结果

 

2、箭头函数不用绑定

箭头函数可以直接完成bind绑定(它会绑定当前scope的this引用),

bind将事件操作和函数处理建立联系,bind和箭头函数都能完成这一绑定。不过箭头函数是ES6的特色,

 

3、ES5语法React.createClass会自动绑定this,ES6的写法不再自动绑定this

绑定this有以下方法:

1.在constructor中进行函数绑定

2.将自定义的函数写成箭头函数形式

3.在调用函数的时候就绑定

4.在调用函数的时候写成箭头函数

如果不想bind(this)就直接使用箭头函数

详情参考:React Native绑定this(bind(this))

 

参考资料:

React/React Native 的ES5 ES6写法对照表

React Native bind方法 和 () => 函数(ES6)

 

posted @ 2021-11-19 17:17  小菜看代码  阅读(655)  评论(0编辑  收藏  举报