由于我是 JavaScript 和 React 的新手,我真的很难找出正确的语法。
这是我的问题:
_handleDrop(files)
应该调用函数 _validateXML(txt)
但实际上没有。我收到此错误 Uncaught TypeError: this._validateXML is not a function
并且无法弄清楚原因。
回调 _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>
);
}
}
最佳答案
当您使用 ES6 类而不是 React.createClass 时,它不会自动绑定(bind) this。
原因:
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.
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
在这种情况下您可以做的是将 this 绑定(bind)到您的 _handleDrop 函数,例如:
<Dropzone onDrop={this._handleDrop.bind(this)} multiple={false}>
您还可以从构造函数中删除函数的分配。
关于javascript - React TypeError this._test 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33872361/