React TypeError this._test不是函数

Dan*_*rch 9 javascript syntax-error ecmascript-6 reactjs

由于我是JavaScript和React的新手,我在确定正确的语法时确实遇到了问题.

这是我的问题:

_handleDrop(files)应该调用函数_validateXML(txt)但不调用.我收到此错误Uncaught TypeError: this._validateXML is not a function,无法弄清楚原因.callBack _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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*mon 12

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

之所以:

React.createClass具有内置的魔术功能,可以自动为您绑定所有方法.这对于那些不使用此功能在其他类JavaScript开发人员有点混乱,或者当他们从应对其他类移动它可能会造成混淆.

因此我们决定不将这个内置到React的类模型中.如果需要,您仍然可以在构造函数中显式预绑定方法.

另请参阅: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}>
Run Code Online (Sandbox Code Playgroud)

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