我有这个简单的代码。 app.jsx
import { test } from './functions'
test()
和functions.jsx
var test
test = () => {
console.log(this.state)
}
export { test }
这给了我: TypeError:_this未定义
所以我尝试像这样绑定它:
this.test = this.test.bind(this)
在我的app.jsx构造函数中,但发生相同的错误。
答案 0 :(得分:1)
您不能将此功能绑定到箭头功能。
箭头函数表达式的语法比函数短 表达式并按词法绑定此值(不绑定自身的值) 此,参数,super或new.target)。箭头功能始终 匿名。
这应该有效:
const test = function() {
console.log(this.state)
}
export { test }
像这样打电话:
// react comp
constructor(props) {
super(props)
this.test = test.bind(this)
this.test();