React中this丢失的四种解决方法
2019-03-28 11:00
453 查看
发现问题
我们在给一个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 来怼,遇到一些小问题记录于此
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。
您可能感兴趣的文章:
相关文章推荐
- U盘强制拔出丢失数据的恢复方法(U盘写保护的四种解决方法)
- mysql error1103 Host * is not allowed to connect to this MySQL server解决方法
- module compiled against API version 9 but this version of numpy is 7的解决方法
- Visual Studio 2010出现error LNK1123 以及 mfc100ud.dll丢失的解决方法
- 无法启动此程序 因为计算机中丢失highgui244d.dll的解决方法
- 关于解决HTTP Status 405 - HTTP method POST is not supported by this URL方法之一
- android R文件丢失解决方法
- 各类unix和linux密码丢失解决方法
- OLEDB方式读取Excel丢失数据、字符串截断的原因和解决方法
- VMWar 安装Centos 7 (32位) 出现丢失网卡设备的解决方法
- [讨论] 这几天来封装Win7用户配置文件丢失的解决方法个人心得
- No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?解决方法
- Oracle number类型查询精度丢失的解决方法
- org.hibernate.TransientObjectException: The instance was not associated with this session解决方法
- linux操作系统root管理员用户密码丢失之解决方法!
- 服务器不能启动的四种解决方法
- C/C++中退出线程的四种解决方法
- MySQL This function has none of DETERMINISTIC, NO SQL...错误1418 的原因分析及解决方法
- **远程连接MySQL提示Host is not allowed to connect to this MySQL server解决方法 以及MySQL命令行闪退问题**
- MySQL下PID文件丢失的相关错误的解决方法