React TypeError this._test 不是函数

React TypeError this._test is not a function

因为我是 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 时,它不会自动绑定 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

在这种情况下,您可以将其绑定到您的 _handleDrop 函数,例如:

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

您还可以从构造函数中删除函数的赋值。

我们解决这个问题的方法是使用一个实验性的 es7 功能,它允许你在 class:

中以这种方式声明一个函数
handleExpandCollapse = () => {
    this.setState({
      isExpanded: !this.state.isExpanded,
    });
  }

这是自动绑定到此的,因此您的 JSX 将是相同的。

此外,当某人将函数向下传递给名称错误的子组件时,也可能发生此错误(不在问题提问的上下文中),即未定义在子组件中访问的函数,因为拼写错误。

我来这里是为了解决这个问题,但发现我也是如此。 :) 希望对大家有所帮助。