2015-11-23 71 views
3

由于我是JavaScript和React的新手,我确实遇到了解决正确语法的问题。React TypeError this._test不是一个函数

这里我的问题:

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

回答

4

当你使用ES6类,而不是React.createClass,它不autobind 这个

的原因所在:

React.createClass有一个内置的神奇功能,可以自动绑定的所有方法 这个给你。这对于 类别中的其他 类别中未使用此功能的JavaScript开发人员可能有点混淆,或者当他们从React移动到其他 类别时,可能会引起混淆。

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

另见:http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

,你可以在这种情况下做的这是什么绑定到您的_handleDrop功能,如:

您也可以从你的构造函数删除功能的分配。

0

我们解决这一问题的方法是使用一个实验ES7功能,它可以让你在这样一个函数声明一个类中:

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

,这是autobound到这一点,所以你JSX会是相同的。

相关问题