当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React中this丢失的四种解决方法

React中this丢失的四种解决方法

2019年03月18日  | 移动技术网IT编程  | 我要评论

发现问题

我们在给一个dom元素绑定方法的时候,例如:

<input type="text" ref="myinput" accept = "image/*" onchange = {this.selectfile} />

react组件中不能获取refs的值,页面报错提示:uncaught typeerror: cannot read property 'refs' of null or undefind

小栗子

import react from 'react';
import $ from 'jquery'
import '../app.scss';

export default class myform extends react.component {
 submithandler (event) {
  event.preventdefault();
  console.log(this.refs.helloto);
  var helloto = this.refs.helloto.value;
  alert(helloto);
 }
 render () {
  return (
   <form onsubmit={this.submithandler}>
     <input ref='helloto' type='text' defaultvalue='hello world! ' />
     <button type='submit'>speak</button>
    </form>
  )
 }
}

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

解决

解决方案有4种

1、在es6中可以在构造函数中,直接将当前组件(或者叫类)的实例与函数绑定。

2、在方法调用的时候绑定this

如: <input type="file" ref="myinput" accept = "image/*" onchange = {this.selectfile.bind(this)} />

3、在方法编写结尾的时候绑定this,bind(this)

如:

submithandler(){
 console.log(1)
}.bind(this)

4、使用es6 箭头函数 myfn = () =>{ console.log(this.refs.can) }

推荐使用箭头函数,因为最近刚换到react 来,没怎么看就直接cli 来怼,遇到一些小问题记录于此

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网