我最近开始学习反应。我正在尝试制作秒表,以下是代码。
import React, {
Component
} from 'react'
class Timer extends Component {
constructor(props) {
super(props);
this.state = {
minutes: 0,
seconds: 0,
};
this.startTimer = this.startTimer.bind(this)
this.stopTimer = this.stopTimer.bind(this)
this.changingTime = this.changingTime.bind(this)
}
startTimer() {
let d = new Date();
let startMin = d.getMinutes();
let startSec = d.getSeconds();
this.myVar = setInterval(this.changingTime(startMin, startSec), 1000)
}
changingTime(min, sec) {
let date = new Date();
this.setState({
minutes: date.getMinutes() - min,
seconds: date.getSeconds() - sec
})
}
stopTimer() {
clearInterval(this.myVar);
}
render() {
return(<div><p> I am timer </p>
<
Timing minutes = {
this.state.minutes
}
seconds = {
this.state.seconds
}
/> <
p > minutes < /p>
<
button onClick = {
this.startTimer
} > Start < /button> <
button onClick = {
this.stopTimer
} > Stop < /button> < /
div >
);
}
}
class Timing extends Component {
render() {
return ( <
h6 > {
this.props.minutes
}: {
this.props.seconds
} <
/h6>
);
}
}
export default Timer;
我在App.js中添加了<Timer/>
。我使用create-react-app创建了应用程序。页面加载并显示加载时需要显示的内容。但秒表不能按预期工作。
this is the screenshot。如您所见,页面正确加载但之后不起作用。控制台显示bundle.js加载失败错误。但我无法理解这是不正确工作的原因还是我的代码有问题。