React TypeError this._test is not a function

Since im new for JavaScript and React, I really have problems figuring out the correct syntax.

Here is my problem:

_handleDrop(files)should call a function _validateXML(txt), but it is not. I get this error Uncaught TypeError: this._validateXML is not a functionand cannot understand why. Callback _handleDrop(files)works great.

When I try to use this syntax _validateXML:function(txt), I immediately get a compilation error. Is it because of 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>
    );
  }
}
+4
source share
2 answers

When you use ES6 classes instead of React.createClass, it does not autobind this .

Cause:

React.createClass , . JavaScript, , , .

React . prebind , .

.: http://facebook.imtqy.com/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

, _handleDrop, :

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

.

+5

es7, :

handleExpandCollapse = () => {
    this.setState({
      isExpanded: !this.state.isExpanded,
    });
  }

, JSX .

0

Source: https://habr.com/ru/post/1617077/


All Articles