React 事件处理程序中 this 的值 [英] Value of this in React event handler

查看:39
本文介绍了React 事件处理程序中 this 的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,它的值在反应事件处理程序中丢失了.阅读文档我认为 react 在这里做了一些事情以确保将其设置为正确的值

For some reason the value of this is being lost in react event handler. Reading the docs I thought that react did some stuff here to make sure this was set to the correct value

以下内容不符合我的预期

The following doesn't work as I'd expect

import React from 'react';

export default class Observer extends React.Component {

    handleClick() {
        console.log(this); //logs undefined
    }
    render() {
        return (
            <button onClick={this.handleClick}>Click</button>
        );
    }
}

但这确实是:

import React from 'react';

export default class Observer extends React.Component {

    handleClick() {
        console.log(this); //logs Observer class instance
    }
    render() {
        return (
            <button onClick={this.handleClick.bind(this)}>Click</button>
        );
    }
}

React 和 ES6 对我来说是新手,但这似乎不是正确的行为?

React and ES6 is new to me but this seems to not be the correct behaviour?

推荐答案

如果您使用新的 class 语法,这是 JavaScript 和 React 的正确行为.

This is correct behavior for JavaScript and React if you use the new class syntax.

自动绑定功能不适用于 v0.13.0 中的 ES6 类.

所以你需要使用:

 <button onClick={this.handleClick.bind(this)}>Click</button>

或者其他技巧之一:

export default class Observer extends React.Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    /* ... */
  }
  render() {
      return <button onClick={this.handleClick}>Click</button>
  }
}

这篇关于React 事件处理程序中 this 的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆