在反应组件中渲染Phaser.io画布

Try*_*nJS 6 javascript reactjs phaser-framework

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

所以我创建了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>
Run Code Online (Sandbox Code Playgroud)

画布正在目标元素之外呈现.

而且,我的this.create功能,我从来没有真正进入那里.我console.log但它永远不会进入.

我正在重新阅读代码,对我来说这一切都有意义,它应该有效,但我不明白为什么它不是.

谁能给我一些指导?

and*_*ood 3

您没有提及您正在使用的 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);
Run Code Online (Sandbox Code Playgroud)

````

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

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

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

create() {
//do stuff
} 
Run Code Online (Sandbox Code Playgroud)

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

this.create.bind(this) 
Run Code Online (Sandbox Code Playgroud)

你应该阅读 ES6 类中的 React 文档范围。这里有一节介绍了为什么绑定 this 对于事件是必要的,这与您需要在此处执行此操作的原因相同

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