Reactjs &引用;这";在另一个函数返回的匿名函数中未定义

Reactjs &引用;这";在另一个函数返回的匿名函数中未定义,reactjs,Reactjs,我已开始学习React,并拥有以下组件: import React, { Component } from 'react'; class Test extends Component{ handler(){ console.log(this); return function(){ console.log(this); } } render(){ {this.handler()()}

我已开始学习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;
当此组件安装在浏览器中时,控制台将打印处理程序返回的函数中未定义的

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


谢谢大家!

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

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

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;

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

如果希望
等于外部函数中
的值,请使用箭头函数

handler(){
    console.log(this);
    return () => {
        console.log(this);
    }
}
或者您可以使用
调用
函数

{this.handler().call(this)}
有关调用函数的更多信息,请参阅


您也可以使用或。这些函数之间有一些细微的差别,您可以在MDN文档中阅读。

或者您可以事先绑定函数
const binded=thisFunction.bind(this)