Reactjs 无法访问函数是嵌套调用(React)

Reactjs 无法访问函数是嵌套调用(React),reactjs,jsx,Reactjs,Jsx,import React,{Component}来自'React'; 从“./Login”导入登录名; 从“./ChatScreen”导入ChatScreen 导出默认类应用程序扩展组件{ 建造师(道具){ 超级(道具) 此.state={ 伊斯洛格丁:错 } } getLoginStatus(状态){ this.setState({isLoggedIn:status}); } showScreen(){ if(this.state.isLoggedIn) 返回( {this.getLoginS

import React,{Component}来自'React';
从“./Login”导入登录名;
从“./ChatScreen”导入ChatScreen
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具)
此.state={
伊斯洛格丁:错
}
}
getLoginStatus(状态){
this.setState({isLoggedIn:status});
}
showScreen(){
if(this.state.isLoggedIn)
返回(
{this.getLoginStatus(status)}}/>)
else if(this.state.isLoggedIn==false)
返回(
{this.getLoginStatus(status)}}/>
)
}
render(){
返回此文件。showScreen()
}
}

从“React”导入React,{Component};
导出默认类应用程序扩展组件{
componentDidMount(){
document.getElementById(“signOut”).addEventListener(“单击”,this.logOut.bind(this));
}
注销(状态){
//假设您的checkStatus方法在props中
var me=this;//在此处保存组件的上下文
var auth2=gapi.auth2.getAuthInstance();
auth2.signOut().then(函数()){
//这里指向注销后的回调方法
//已经完成了它的任务。所以这将指向
//上下文。
控制台日志(“输出日志”);
me.props.checkStatus(false);//这里我们使用了保存的上下文
//因此,我们可以访问所需的方法。
});
}
render(){
退出
}
}

在调用
checkStatus

之前,只需保存应用程序的上下文即可。您的checkStatus方法在哪里?它位于父组件中,我已更新了该问题。具体问题尚不清楚。答案也是如此。这个问题既有一个公认的答案,也有一个不同的答案。这个问题涉及对javascript中上下文传递的基本理解。我只是想知道“这个”在不同的情况下适用。我是在将函数作为参数传递时了解到绑定的,默认情况下arrow函数会这样做。所以这两个答案都是正确的。我对这一点很陌生。那么你能告诉我怎么做吗?其实这不是关于react js,而是关于Javascript是如何工作的。您正在尝试以不同的功能访问此。在您的案例中,这是签出api的回调函数,因此在签出完成后,
将具有回调方法的上下文,这在案例中不同于您的React组件上下文,我想你可能对此感到困惑。得到了关于理解这是如何在函数中传递的答案,希望你对上下文的理解是正确的。希望它解决了你的问题,然后你可以标记它的解决方案!此外,为了您的清晰,我在解决方案中添加了注释。我在下面添加了解决方案,以帮助其他人检查它。这是非常有效和正确的。
import React, { Component } from 'react';

export default class App extends Component {

    componentDidMount() {
        document.getElementById("signOut").addEventListener("click", this.logOut.bind(this));
    }

    logOut(status) {
        // Supposing your checkStatus method is in props
        var me = this; //Saving Context of your Component here
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function() {
            // this here points to the callback method after signOut
            // has performed its task. So this will point to that
            // context. 
            console.log("outlog");
            me.props.checkStatus(false); // Here we used the context saved 
            //above so we can access the required method.
        });

    }

    render() {
        return <button id = "signOut" > out < /button>
    }
}