javascript - React TypeError this._test 不是一个函数

标签 javascript reactjs syntax-error ecmascript-6

由于我是 JavaScript 和 React 的新手,我真的很难找出正确的语法。

这是我的问题:

_handleDrop(files) 应该调用函数 _validateXML(txt) 但实际上没有。我收到此错误 Uncaught TypeError: this._validateXML is not a function 并且无法弄清楚原因。 回调 _handleDrop(files) 工作正常。

当我尝试这种语法 _validateXML:function(txt) 时,我在编译时立即收到错误消息。是因为 ecmascript 吗?

import React from 'react';
import './UploadXML.scss';
import Dropzone from 'react-dropzone';
import xml2js from 'xml2js';

export default class UploadXML extends React.Component {

  constructor() {
    super();
    this._validateXML = this._validateXML.bind(this);
  }

  _validateXML(txt) {
    console.log('Received files: ', txt);
  }

  _handleDrop(files) {
    if (files.length !== 1) {
      throw new Error("Please upload a single file");
    }
    var file = files[0];

    console.log('Received files: ', file);

    this._validateXML(file);
  }

  render() {
    return (
      <div>
            <Dropzone onDrop={this._handleDrop} multiple={false}>
              <div>Try dropping some files here, or click to select files to upload.</div>
            </Dropzone>
      </div>
    );
  }
}

最佳答案

当您使用 ES6 类而不是 React.createClass 时,它不会自动绑定(bind) this

原因:

React.createClass has a built-in magic feature that bound all methods to this automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.

Therefore we decided not to have this built-in into React's class model. You can still explicitly prebind methods in your constructor if you want.

另见:http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

在这种情况下您可以做的是将 this 绑定(bind)到您的 _handleDrop 函数,例如:

<Dropzone onDrop={this._handleDrop.bind(this)} multiple={false}>

您还可以从构造函数中删除函数的分配。

关于javascript - React TypeError this._test 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33872361/

相关文章:

javascript - nuxt 身份验证 : Google provider return invalid_request

javascript - 如何在 Chrome 中创建 TouchEvent?

javascript - 如何在 onClick 事件中使用 ReactJS 淡出/淡入内容?

javascript - typescript 错误#70006,类型引用任何

debugging - 如何调试一般 YAML 语法错误的 ansible 没有详细信息文件并且很可能与剧本本身无关?

sql - 在 Oracle 中创建一个列具有默认值的表

javascript - 从经典 .ASP 重复区域调用正确的、单独的模态菜单

javascript - jquery mobile 设置单选按钮组的选定值

javascript - JS React 网站最好的无限滚动工具/组件?

python-3.x - Python为什么在else语句后用错误消息响应?