繁体   English   中英

在导出的React函数中未定义“ this”

[英]“this” undefined in exported react function

问题:当我的React组件调用导出的函数时, console.log(this)显示未定义。 我一直期望它返回组件,因为我已经将其绑定在构造函数中。

Leaderboard.js:

import React from 'react';
import {leaderboard, createLeaderboard} from '../utility/gamecode';

class Leaderboard extends React.Component{
  constructor(props){
    super(props);
    this.showLeaderboard = showLeaderboard.bind(this);
    this.state = {
    }
  };

  componentDidUpdate(){
    if(this.props.leaderboard){
      showLeaderboard();
    }
  }

  render(){
    return(
      <div className="leaderboard hidden">
      </div>
    )
  }

}

export default Leaderboard;

gamecode.js:

export function showLeaderboard(){
 console.log(this);
}
//-----------------------
export function createLeaderboard(props){
}

您呼叫showLeaderboard而不是this.showLeaderboard -您绑定的一个this来。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM