react-native react 中的bind(this)

bind的概念

bind是javascript函数中常用的一个功能。

bind()方法创建一个新的函数, 当被调用时,将其this关键字设置为提供的值,在调用新函数时,在任何提供之前提供一个给定的参数序列。

以下是bind最简单的用法:

this.x = 9; 
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 返回 81

var retrieveX = module.getX;
retrieveX(); // 返回 9, 在这种情况下,"this"指向全局作用域

// 创建一个新函数,将"this"绑定到module对象
var boundGetX = retrieveX.bind(module);
boundGetX(); // 返回 81

bind函数到底做了什么操作,能使this绑定到我们需要绑定的对象当中?其实也就类似以下代码:

   Function.prototype.bind = function (scope) {
     var fn = this;
     return function () {
       fn.apply(scope);
     }
   } 

返回新建了一个函数,并把需要绑定的作用域传递到这个新函数上。

React中的bind

在React或React-native的点击事件中,会经常用到bind(this)。
比如说一个简单的React-native点击组件:

export default class AwesomeProject extends Component {
  constructor(props){
    super(props);
    this.state = {
    }
  }

  handleClick () {
    console.log('this is:',this);
  }

  render() {
    return (
      container}>
        this.handleClick.bind(this)}>
          Welcome to React Native!
        
      
    );
  }

}

在上面的代码中,我们对点击事件函数进行了bind(this),如果不bind(this)的this会怎么样?
react-native react 中的bind(this)_第1张图片
react-native react 中的bind(this)_第2张图片
上图是bind了this的,而下图是没有bind(this)的。如果没有bind(this),在执行这个函数时,取到的this是这个text组件。

React中的bind方法的选择

因为箭头函数与bind(this)的作用是一样的,所以我们可以有4种选择

  //写法1
  this.handleClick.bind(this)}>

  //写法2
  constructor(props){
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  //写法3
  ()=>this.handleClick()}>

  //写法4
  handleClick = () => {

  }

因为bind方法会重新生成一个新函数,所以写法2和写法3每次render都会生成新的函数,所以建议使用1或4

你可能感兴趣的:(javascript)