2015-11-23 113 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會是相同的。

相關問題