在我的组件中,我正在调用另一个文件中定义的函数,如下所示:
import React from 'react';
import { widgetComponentDidMount } from "../../SharedData/widget";
export default class Component extends React.Component {
constructor(props) {
super(props);
};
componentDidMount(){
widgetComponentDidMount(this).bind(this);
}
//render, etc
};
但是当我将调试器放入函数的定义中时,“this”未定义:
export function widgetComponentDidMount() {
var _this = this;
debugger
//_this is undefined
}
我知道我可以将其作为参数传递并以这种方式引用它,但我宁愿避免每次都传递它。这不就是bind的目的吗?我只能在同一个文件中使用它。知道为什么它未定义以及如何访问“this”而不将其作为参数传递吗?
最佳答案
您在调用bind
之前执行该函数。您必须在执行之前绑定(bind):
widgetComponentDidMount.bind(this)();
如果是我,我实际上会在构造函数方法中执行 bind
并存储结果,这样您就不需要为每次调用创建一个新函数:
export default class Component extends React.Component {
constructor(props) {
super(props);
this.widgetComponentDidMount = widgetComponentDidMount.bind(this);
}
componentDidMount() {
this.widgetComponentDidMount();
}
}
关于javascript - 为什么调用 .bind(this) 时函数中 this 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40030924/