我无法帮助您如何在setInterval中返回jsx,但有一种简单的方法可以解决您的问题。您将拥有一个名为
distance
。每秒钟都会减少这种状态。在“渲染”中,检查“距离”的值并渲染所需的内容。下面是示例代码
constructor(props) {
//calc countDownDate
//now can access props
this.state = {
distance: countDownDate - now;
}
}
componentDidMount() {
this.countDown = setInterval(() => {
const {distance} = this.state
//Calc the new distance
if(distance < 0) {
clearInterval(this.countDown)
}
this.setState({distance: newDistance})
}, 1000)
}
componentWillUnount() {
clearInterval(this.countDown)
}
render() {
const {distance} = this.state
if (distance === 0) {
return (
<button className="message button clickable" onClick={start}>Click to Start Call </button>
);
} else if (distance > 0) {
return (
<p> <b>Appointment starts in :</b> <span>{countdown}</span></p>
);
} else if (distance < 0) {
return (
<h2>Appointment Expired</h2>
);
};
}