发现问题
我们在给一个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 来怼,遇到一些小问题记录于此
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 群星《十二女声Ⅲ》[WAV/CUE/分轨][626.4MB]
- 陈百强.1993-离不开...纪念歌集2CD【华纳】【WAV+CUE】
- 于台烟.2003-爱自己【乾坤唱片】【WAV+CUE】
- 群星.2024-我们永远是我们电影原声带【乐禾发文化】【FLAC分轨】
- 【中国民乐】张维良《秋江夜泊》2004[FLAC+CUE]
- 明达年度发烧碟MasterSuperiorAudiophile2011[DSF]
- 明达年度发烧碟MasterSuperiorAudiophile2017[DSF]
- 翁立友.2008-恨孤单【大旗】【WAV+CUE】
- 群星.2009-Magic.Cover日粤精华3CD【环球】【WAV+CUE】
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]