react中为什么要bind?bind的三种方法

react中为什么要bind?bind的三种方法

为什么?1.JavaScript自身特性说明如果传递一个函数名给一个变量,之后通过函数名()的方式进行调用,在方法内部如果使用this则this的指向会丢失。

示例代码:

首先我们创建test对象并直接调用方法 :

const test = {

name:'jack',

getName:function(){

console.log(this.name)

}

}

test.getName()

const test = {

name:'jack',

getName:function(){ console.log(this.name)

}

}

test.getName()

使用node test.js执行上述代码可以正常输出jack。

之后,我们对代码进行调整:

const test = {

name:'jack',

getJack:function(){

console.log(this.name)

}

}

const func = test.getJack;

func();

我们没有直接调用对象的方法,而是将方法声明给一个中间变量,之后利用中间变量()调用方法,此时this则失去指向,输出undefined,如果使用node环境执行js文件则输出node相关信息,如嵌入到html中则this指向window对象。

2.React事件绑定React中的bind同上方原理一致,在JSX中传递的事件不是一个字符串,而是一个函数(如:onClick={this.handleClick}),此时onClick即是中间变量,所以处理函数中的this指向会丢失。解决这个问题就是给调用函数时bind(this),从而使得无论事件处理函数如何传递,this指向都是当前实例化对象。

当然,如果不想使用bind(this),我们可以在声明函数时使用箭头函数将函数内容返回给一个变量,并在调用时直接使用this.变量名即可。示例代码如下:

import React from 'react';

export default class Life extends React.Component{

constructor(props){

super(props);

this.state = {

count:4

};

}

render(){

var style = {

padding:'10px',

color:'red',

fontSize:'30px'

}

return (

{/*注意js语法使用一个括号{}去表示,style使用两个括号,原因里面其实是一个对象*/}

React生命周期介绍

{this.state.count}

)

}

//此时this指向是当前实例对象

handleAdd = ()=> {

console.log(this)

this.setState({

count:5

})

}

handleClick(){

this.setState({

count:6

})

}

}

REACT 函数BIND(THIS)的三种方式

1.在调用地方直接bind(this)

handleClick(){

this.setState({

word2:'word2 changed'

})

}

2、使用ES6 箭头函数

handleClick=()=>{

this.setState({

word2:'word2 changed'

})

}

3、构造函数中bind(this)

constructor(props){

super(props);

this.state=({

word2:'word2'

})

this.handleClick = this.handleClick.bind(this);

}

相关推荐