我是新来的使用React和作为练习试图修改时钟示例 从React's splash page。我们的目标是在一个时间间隔内计算秒数,并以更快的间隔更改圆圈的颜色。反应和多个定时事件
我曾尝试用setTimeout
功能的更改圈 要做到这一点,并呼吁他们从tick
函数中,但setTimeout
通话不被 认可。
这是React的问题,setInterval
与setTimeout
冲突? 如果是这样,实现偏移定时事件的最佳方式是什么?
谢谢你的时间。
<!doctype html>
<html>
<head>
<title>Timer</title>
<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<link rel="stylesheet" href="styles.css" >
</head>
<body>
<div id="root"></div>
</body>
<script type="text/babel">
var changed = false;
class GameDisplay extends React.Component{
constructor(props){
super(props);
this.colorChange = this.colorChange.bind(this);
this.state = {
secondsElapsed: 0,
};
}
tick(){
setTimeout(() => this.colorChange(), 250);
setTimeout(() => this.colorChange(), 250);
this.colorChange();
this.setState((prevState) => ({
secondsElapsed: prevState.secondsElapsed + 1,
}));
}
colorChange(){
var tgt = document.getElementById("heart");
if (changed){
tgt.style.fill = "red";
} else {
tgt.style.fill = "green";
}
changed = !changed;
}
componentDidMount(){
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount(){
clearInterval(this.interval);
}
render(){
return(
<div>
<h1>Seconds Elapsed: {this.state.secondsElapsed}</h1>
<svg id="main_disp" width="300" height="300">
<circle cx="150" cy="150" r="50" fill="black" />
<circle id="heart" cx="150" cy="150" r="30" fill="red" />
</svg>
</div>
);
}
}
class App extends React.Component {
render(){
return(
<div>
<GameDisplay />
</div>
)
};
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
</script>
</html>
Mehiel非常感谢你的时间和引用,这是一个很大的帮助。谢谢。 – Cameron