我开始学习react.js,并在react应用程序中开发了一个简单的石头剪刀布游戏。我发现创建一个重新加载按钮有点困难,因为它当然与具有如下功能的 javascript 按钮不同:
<button onclick="reload">RESTART GAME</button>
function reload() {
location.reload();
}
对于这个反应应用程序,我认为可行的是:
<button type="button" onClick={ refreshPage }> <span>Reload</span> </button>
function refreshPage(){
window.location.reload();
}
到 App.js 文件,但我收到错误消息:
./src/App.js
Syntax error: Unexpected token (64:11)
62 | }
63 |
> 64 | function refreshPage(){
| ^
65 | window.location.reload();
66 | }
67 | }
完整的项目可以在这里找到github https://github.com/tobi-ajala/react-rockpaperscissors(npm start 将在终端/控制台中启动项目)
任何有关如何纠正此问题的见解将不胜感激,谢谢!
在反应中,您不必刷新页面来重置状态。我查看了您的项目,发现您将分数和游戏数据保存在组件的状态中。这可以帮助您轻松重置游戏,只需将状态设置为初始值即可。
例如
// add a method to your component for resetting state
restartGame(event) {
this.setState({ games: [] });
}
// and in your components render or any other place add the reset button
<button type="button" onClick={ this.restartGame.bind(this) }>
<span>Reload</span>
</button>
不要忘记绑定您的方法以便能够使用this
在他们中。有关更多信息,您可以阅读 React 文档处理事件 https://reactjs.org/docs/handling-events.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)