【问题标题】:Rendering Phaser.io canvas in a react component在反应组件中渲染 Phaser.io 画布
【发布时间】:2018-12-29 13:20:20
【问题描述】:
import React, { Component } from 'react';
import Phaser from 'phaser';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.game = null;
    this.create = () => {
      this.game.stage.backgroundColor = '#124184';
    }
  }

  componentDidMount() {
    this.game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-target',
      {
        create: this.create
      }
    );

    console.log(this.create);
  }

  render() {
    return (
      <section id="phaser-target">
        hello there old friend
      </section>
    )
  }
}

所以我创建了 Phaser 游戏对象,在组件中做了 mount 方法,注意我的html 看起来像这样:

<body style="overflow: hidden;">
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"><section><section id="phaser-target">hello there old friend</section></section></div>

  <script type="text/javascript" src="/static/js/bundle.js"></script>

<canvas width="1024" height="768"></canvas></body>

画布正在目标元素之外渲染。

还有,我的this.create 函数,我从来没有真正进入过那里。我console.log 但它永远不会进入。

我正在重新阅读代码,对我来说这一切都很有意义,它应该可以工作,但我不明白为什么不能。

谁能给我一些指导?

【问题讨论】:

    标签: javascript reactjs phaser-framework


    【解决方案1】:

    您没有提及您使用的是哪个版本的 Phaser,这非常重要,因为这些年来 API 已经多次更改。

    此答案假设您使用的是当前最新版本的 Phaser (3.1.4)

    ```

    var config = {
        type: Phaser.AUTO,
        parent: 'phaser-parent',
        pixelArt: true,
        width: 800,
        height: 600,
        scene: {
            preload: this.preload.bind(this),
            create: this.create.bind(this)
        }
    };
    
    var game = new Phaser.Game(config);
    

    ```

    将父配置设置为您的移相器父的 id。它应该附加到正确的元素。

    我猜问题是 Phaser 没有检测到这一点并自动附加到文档正文元素。

    要正确调用 create 方法,您应该创建一个普通的 ES6 类方法:

    create() {
    //do stuff
    } 
    

    现在你应该用 bind(this) 来调用它:

    this.create.bind(this) 
    

    您应该阅读 ES6 类中的 React 文档范围。这里有一个部分说明为什么绑定 this 对事件来说是必要的,这与你需要在这里做的原因是一样的

    https://reactjs.org/docs/handling-events.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多