React学习笔记——Class组件内this的指向undefined及解决办法

一、React当中Class组件内的this指向

所有在类中定义的方法都默认开启局部严格模式,所以在Class组件当中

  • 所以指向window对象的this都指向undefined
  • 所有内联的的事件处理处理函数当中的this都指向undefined
<script type="text/babel">
    
	class Toggle extends React.Component {
	  constructor(props) {
	    super(props);
	    this.state = {isToggleOn: true};
		console.log(1,this) //this指向组件实例
	  }
	
	  handleClick() {
		console.log(this)  //undefined
	    this.setState(state => ({
	      isToggleOn: !state.isToggleOn
	    }));
	  }
        
	 //React.Component 的子类中有个必须定义的 render() 函数,
     //render将会在constructor构造函数之后执行
	 render() {
        console.log(this)
	    return (
		//handleClick在代码中是作为onClick的回调,所以不是通过实例调用的,是直接调用的
		//类中的方法默认开启了局部的严格模式,因此handleClick中的this为undefined
	      <button onClick={this.handleClick}>
	       {this.state.isToggleOn ? 'ON' : 'OFF'}
	      </button> -->
	    );
	  }
	}
	
	ReactDOM.render(
	  <Toggle />,
	  document.getElementById('root')
	);
</script>

二、React当中Class组件this指向undefined的解决方法

  • 第一种:通过bind方法改变this的指向

    1、在construstor构造函数当中修改:

    	constructor(props) {
    	    super(props);
    	    this.state = {isToggleOn: true};
            // 为了在回调中使用 `this`,重新绑定为这个Toggle组件实例
    	    this.handleClick = this.handleClick.bind(this);
     	}
    

    2、在内联的jsx语法当中直接使用

    	render() {
            console.log(this)
    	    return (
    	      <button onClick={this.handleClick.bind(this)}>
    	       {this.state.isToggleOn ? 'ON' : 'OFF'}
    	      </button> -->
    	    );
    	  }
     	}
    
  • 第二种:通过箭头函数的方式

    1、在定义的地方使用箭头函数

     handleClick = () => {
    	    this.setState(state => ({
    	      isToggleOn: !state.isToggleOn
    	    }));
    	 }  
    

    2、在jsx事件模板当中使用

     render() {
    	    return (
    		//handleClick在代码中是作为onClick的回调,所以不是通过实例调用的,是直接调用的
    		//类中的方法默认开启了局部的严格模式,因此handleClick中的this为undefined
    	     <button onClick={()=>this.handleClick()}>
    	       {this.state.isToggleOn ? 'ON' : 'OFF'}
    	      </button>
    	    );
    }
    

    注:js当中严格模式下的this指向参照——Js当中严格模式下,常见的this指向

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值