我正在使用react開發一個簡單的遊戲鬥爭動畫。要開始戰鬥,我有一個按鈕onClick
事件:onClick={this.fight.bind(this)}
。現在,我想在這樣的事隨時變化更新一些狀態變量:在onClick方法中反應setState不更新DOM
import React, { Component } from 'react';
import { ProgressBar, Row, Col } from 'react-bootstrap';
const playerA = {
_id: 1,
name: "playerA name",
life: 100,
speed: 50,
}
const playerB = {
_id: 1,
name: "playerB name",
life: 100,
speed: 40,
}
export default class App extends Compornent {
constructor() {
super();
this.state={
playerA : playerA ,
playerB : playerB ,
aLife: 100,
bLife: 100,
};
this.fight = this.fight.bind(this);
};
fight(a,b){
lifeA=this.state.playerA.live;
lifeB=this.state.playerB.live;
speedA=this.state.playerA.speed;
speedB=this.state.playerB.speed;
dmg = 10
while (lifeA>0 && lifeB>0) {
if (speedA > speedb) {
lifeA = lifeA - dmg;
setTimeout(() => {
this.setState({ aLife: lifeA });
}, 1000);
speedB = speedB + 10;
} else {
lifeB = lifeB - dmg;
setTimeout(() => {
this.setState({ bLife: lifeA });
}, 1000);
speedA = speedA + 10;
}
}
render() {
return (
<Row>
<ProgressBar bsStyle="success" now={this.state.aLife} srOnly/>
<ProgressBar bsStyle="success" now={this.state.bLife} srOnly/>
</Row>
<Row>
<Button bsStyle="danger" bsSize="large" onClick={this.fight.bind(this)}>Start Fight</Button>
</Row>
);
}
}
我的期望是看到進度條beeing更新每隔1秒。但它只更新一次。當戰鬥功能完成beein執行。
你試圖返回打架功能?剛剛更新的 –
是一個錯誤。只是想要執行該功能並更新狀態 – danyhiol