目标:当我的游戏组件收到道具时,我希望componentDidUpdate()调用一个名为consolelog的函数,该函数是另一个名为gamecode()的函数的子代。

问题:使用this.gameCode.consolelog()总是返回错误,指出consolelog不是gameCode的功能。

注意:Gamecode()是从名为gamecode.js的文件导入到我的react组件(游戏)中的

零件:

import React, {Component} from 'react';

import {gameCode, showLeaderboard} from '../utility/gamecode';

class Game extends Component{
  constructor(props){
    super();
    this.state = {
      drawL : null
    }
  };

  componentDidMount(){
    this.gameCode();
  };

  componentDidUpdate(){
    //will run when the state changes
    if(this.props.leaderboard){
        var a = this.props.leaderboard;
        this.gameCode.consolelog(a);
    }
  }

  render(){
    return(
      <div className="Game">
        <canvas id="canvas"></canvas>
        <button onClick={this.props.getleaderboard} className="showleaders">Show leaderboard</button>
      </div>
    );
  }
}

export default Game;


GameCode.js函数:

gameCode(){
  //the main function initializes some stuff immediately and start running the update() and draw() functions
  const canvas = document.getElementById('canvas');
  canvas.width = 800;
  canvas.height= 600;
  const ctx = canvas.getContext("2d");
  const FPS = 30;
  setInterval(() => {
      update();
      draw();
  }, 1000/FPS);

  //but sometimes I need to call other functions on demand, but these functions depend on what the parent function and other sibling functions
  function consolelog(a){
    console.log("success!");
    console.log(a);
  }
}

最佳答案

您可以使用revealing module pattern的形式。将私有变量的作用域保留在gameCode范围内,并导出所需的公共变量和函数。

const gameCode = (function () {

  const a = 1;

  function consolelog() {
    console.log(`success${a}`);
  }

  return {
    consolelog: consolelog
  }

});

export default gameCode;


在您的其他文件中:

import gameCode from './gameCode';

componentDidMount() {
  const gc = gameCode();
  gc.consolelog(); // success1
}


DEMO

10-04 17:00