【发布时间】:2017-03-21 16:55:51
【问题描述】:
我正在 reactjs 中使用 matter.js 制作游戏。
我遇到了一个问题,我无法在 render() 中返回任何内容。
这可能是因为 matter.js 有自己的渲染器。
所以我没有在渲染部分重新调整任何内容。
如果我在渲染部分没有返回任何内容,componentDidMount 不要运行。
我无法运行 componentDidMount(),即使我绑定它也无法调用任何函数。
我正在调用 start_game() 函数来开始游戏,但是我在 start_game() 中调用的任何其他函数都会出现错误,表明即使我在类中声明了该函数也不存在。
import React, { Component } from 'react';
import Matter from 'matter-js';
const World = Matter.World;
const Engine = Matter.Engine;
const Renderer = Matter.Render;
const Bodies = Matter.Bodies;
const Events = Matter.Events;
const Mouse = Matter.Mouse;
const MouseConstraint = Matter.MouseConstraint;
const Body = Matter.Body;
class Walley extends Component
{
constructor(props)
{
super(props);
this.world = World;
this.bodies = Bodies;
this.engine = Engine.create(
{
options:
{
gravity: { x: 0, y: 0,}
}
});
this.renderer = Renderer.create(
{ element: document.getElementById('root'),
engine: this.engine,
options:
{
width: window.innerWidth,
height: window.innerHeight,
background: 'black',
wireframes: false,
}
});
this.state = {
play_game: false,
score:0,
};
this.play_game=this.play_game.bind(this);
}
play_game(){
this.setState
({
score: 50,
});
}
startGame()
{
console.log(this.state.play_game);
//don't know how here the value of play_game is set to true even it was false in componentWillMount()
if(this.state.play_game){
this.play_game();
//unable to access play_game
}
}
componentWillMount()
{
if (confirm("You want to start game?"))
{
this.setState({play_game: true});
}
console.log(this.state.play_game);
//even though play_game is set true above yet output at this console.log remains false
}
render()
{
if(this.state.play_game)
this.startGame();
}
componentDidMount()
{
//unable to access
console.log('Did Mount');
}
}
export default Walley;
【问题讨论】:
-
一个 React 组件必须总是通过
render()返回一些东西。startGame应该在componentDidMount中调用,因为需要 DOM。建议大家学习React。 -
我已经知道了。我没有故意返回任何东西,因为 matte.js 已经有一个渲染器。我无法创建并返回我自己的。
-
如果您的组件没有要渲染的内容,则无法挂载该组件,因此不会调用 componentDidMount。从设计的角度来看,您可能想要创建一个游戏循环来检查何时开始游戏,或者相应地创建一些动作和调度程序来开始游戏。