“this”在另一个函数 React 返回的匿名函数中未定义

IT技术 reactjs
2021-04-30 04:04:04

我已经开始学习 React 并拥有以下组件:

import React, { Component } from 'react';
class Test extends Component{
    handler(){
        console.log(this);
        return function(){
            console.log(this);
        }
    }
    render(){
       {this.handler()()}
       return null;
    }
}
export default Test;

当这个组件安装在浏览器中时,控制台会打印出thishandler返回的函数内未定义。

如果组件已经安装,我不明白为什么它是未定义的。你们能帮我找到原因和可能的更正吗?

谢谢!

2个回答

this嵌套函数内部将根据它的调用方式确定。由于您没有使用任何对象调用它,this因此嵌套函数内部是未定义的。

如果要this等于this外部函数中的,请使用箭头函数。

handler(){
    console.log(this);
    return () => {
        console.log(this);
    }
}

或者你可以使用call函数

{this.handler().call(this)}

有关调用函数的更多信息,请参阅Function.prototype.call()

您还可以使用Function.prototype.bind()Function.prototype.apply()您可以在 MDN 文档上阅读这些功能之间的细微差别。

this通过函数的调用方式在函数中定义。处理程序函数在this类的 ie 实例上调用,因此this内部处理程序函数将打印您的类实例。然而,返回的函数不是在类实例上调用而是独立调用的,因此这是未定义的

您可以将返回的函数定义为箭头函数,它将引用您想要的正确 this

import React, { Component } from 'react';
class Test extends Component{
    handler(){
        console.log(this);
        return () => {
            console.log(this);
        }
    }
    render(){
       {this.handler()()}
       return null;
    }
}
export default Test;