React TypeError this._test不是函数 [英] React TypeError this._test is not a function

查看:82
本文介绍了React TypeError this._test不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我是JavaScript和React的新手,我在确定正确的语法方面确实存在问题。

Since im new to JavaScript and React, i really have problems figuring out the right syntax.

这里我的问题:

_handleDrop(files)应该调用函数 _validateXML(txt)但不会。我收到此错误未捕获TypeError:this._validateXML不是函数,无法找出原因。
callBack _handleDrop(files)工作正常。

_handleDrop(files) should call the function _validateXML(txt) but doesn't. I receive this error Uncaught TypeError: this._validateXML is not a function and can't figure out why. The callBack _handleDrop(files) works fine.

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

When i try this kind of syntax _validateXML:function(txt) i immediately get a error while compiling. Is that 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>
    );
  }
}


推荐答案

你使用的是ES6类而不是React.createClass,它不会自动绑定这个

When you're using the ES6 classes instead of React.createClass, it does not autobind this.

原因:


React.createClass有一个内置的魔术功能,可以自动将所有方法
绑定到此。对于那些在其他
类中不习惯这个功能的
JavaScript开发人员来说,这可能会有点混乱,或者当他们从React转移到其他
类时会让人感到困惑。

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.

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

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函数,如:

What you could do in this instance is binding this to your _handleDrop function, like:

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

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

You can also remove the assigning of the function from your constructor.

这篇关于React TypeError this._test不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆