@ion phaser/react函数组件的重新初始化将canvas从dom中移除



我在重新初始化父组件中的离子相位器功能组件时遇到问题。通过将其重新初始化为类组件,它可以很好地工作。波纹管是显示哪些有效,哪些无效的两个例子。这是我的父渲染函数:

render() {
return(
<>
{this.state.visible && <IonComponent />}
</>
)
}

这是离子相位器功能组件(不起作用(:

let game = { ..here comes the Phaser game logic }
const IonComponent = () => {
const [initialize, setInitialize] = useState(false);
useEffect(() => {
if (game?.instance === undefined) {
setInitialize(true);
}
}, [initialize]);
return (
<>
{ initialize && <IonPhaser game={game} initialize={initialize} />}
</>
)
}
export default IonComponent;

这是离子相位器类组件(此项工作(:

class IonComponent extends React.Component {
state = {
initialize: true,
game: { ..here comes the Phaser game logic }
}
render() {
const { initialize, game } = this.state
return (
<IonPhaser game={game} initialize={initialize} />
)
}
}
export default IonComponent;

当我在父组件中将第一次渲染时的state.visible切换为true时,它会毫无问题地启动子IonPhaser组件。但是,在state.visible切换一次为false,然后再切换回true之后,函数组件将不会重新初始化,它将从dom中删除画布。但是类组件运行良好。这是Ion Phaser功能组件中的一个持续错误,还是我做错了什么?

确保使用React的useState()钩子或类似的东西跟踪game的状态。

值得一提的是,我在尝试使IonPhaser软件包工作时也遇到了一些问题为了解决这些问题,我在这里发布了一种集成Phaser和React的替代方法,(我认为(更简单。

它的工作方式基本相同,但它没有IonPhaser包那么多开销。

npm i phaser-react-tools

然后您可以将GameComponent导入到App.js文件中,如下所示:

import { GameComponent } from 'phaser-react-tools'
export default function App() {
return (
<GameComponent
config={{
backgroundColor: '000000',
height: 300,
width: 400,
scene: {
preload: function () {
console.log('preload')
},
create: function () {
console.log('create')
}
}
}}
>
{/* YOUR GAME UI GOES HERE */}
</GameComponent>
)
}

它还带有挂钩,可以让您直接从React组件发出和订阅游戏事件。希望这能有所帮助,如果您有反馈,请与我们联系。

我想建议一个更好的解决方案,

这里是phaser3+react+websocket模板,使用这个存储库作为示例。关键功能是二维功能,您可以从场景中调用react控件。调用react组件外部的react钩子:

CONTROLS.setVersion(`Phaser v${Phaser.VERSION}`)

要从react组件调用phaser,您可以使用(从phaser.game.ts导入全局变量(:

import game from "./phaser-game"
(game.scene.game as GameScene).<whatever you want>

https://github.com/tfkfan/phaser3-react-template

所以看看

最新更新