小编典典

反应TypeError this._test不是函数

reactjs

自从我对JavaScript和React感到陌生以来,我确实在找出正确的语法方面遇到了问题。

这是我的问题:

_handleDrop(files)应该调用该函数,_validateXML(txt)但不会。我收到此错误Uncaught TypeError: this._validateXML is not a function,无法找出原因。回调_handleDrop(files)可以正常工作。

当我尝试这种语法_validateXML:function(txt)时,在编译时会立即出现错误。那是因为电子书吗?

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>
    );
  }
}

阅读 263

收藏
2020-07-22

共1个答案

小编典典

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

之所以:

React.createClass具有内置的魔术功能,可以自动为您绑定所有方法。对于不习惯其他类中此功能的JavaScript开发人员,这可能会有些混乱,或者当他们从React移至其他类时,可能会造成混乱。

因此,我们决定不将此内置到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}>

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

2020-07-22