Reactjs 导入的函数可以';我不明白这个
我有这个简单的代码。 app.jsx 以及functions.jsxReactjs 导入的函数可以';我不明白这个,reactjs,Reactjs,我有这个简单的代码。 app.jsx 以及functions.jsx var test test = () => { console.log(this.state) } export { test } 这给了我: TypeError:\u这是未定义的 所以我试着像这样绑定它: this.test = this.test.bind(this) // react comp constructor(props) { super(props) this.test = test.
var test
test = () => {
console.log(this.state)
}
export { test }
这给了我:
TypeError:\u这是未定义的
所以我试着像这样绑定它:
this.test = this.test.bind(this)
// react comp
constructor(props) {
super(props)
this.test = test.bind(this)
this.test();
在app.jsx中的我的构造函数中,出现了相同的错误。您不能将其绑定到arrow函数 与函数相比,箭头函数表达式的语法更短 表达式和词汇绑定此值(不绑定自己的值 此参数(参数、super或new.target)。箭头函数始终为空 匿名的 这应该起作用:
const test = function() {
console.log(this.state)
}
export { test }
这样称呼:
this.test = this.test.bind(this)
// react comp
constructor(props) {
super(props)
this.test = test.bind(this)
this.test();
例如:
虽然如此,但这给了我一个稍有不同的错误:TypeError:这是未定义的。您仍然需要将
此
绑定到上述内容。。是吗?是的,在app.jsx中我的构造函数中仍然有this.test=this.test.bind(this)。我认为您绑定了错误的东西-应该是this.test=test.bind(this)查看我的工作代码沙盒示例-当您调用this.test.bind(this)
时,您应该能够从中计算出来。但是也没有定义此,因为您在函数外部调用它<代码>此仅在函数中定义!你能把它作为一个解决方案提交给我吗?我可以试试。