React中this丢失的解决方法

  • 我们在给一个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)
复制代码
  1. 使用es6 箭头函数 myfn = () =>{ console.log(this.refs.can) }

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

猜你喜欢

转载自juejin.im/post/5c80d552f265da2db414509c
今日推荐