【发布时间】:2017-04-13 20:45:41
【问题描述】:
我正在使用 ReactJS 和 Electron 开发秒表应用程序。我有一个 Timer 组件,它跟踪时间并显示时钟和控件。
控件将由三个按钮组成:播放、暂停和停止。这些 Button 组件与 Timer 组件完全无关。
我的问题是:如果我在 Timer 组件中有一个handleStopClick() 函数,我如何从 StopButton 组件中调用它?
注意:目前没有播放/暂停功能。定时器在安装时简单地启动,一个停止按钮应该清除它。等我整理好之后再补充。
这是 Timer.jsx:
import '../assets/css/App.css';
import React, { Component } from 'react';
import PlayButton from './PlayButton'; // No function
import PauseButton from './PauseButton';
import StopButton from './StopButton';
class Timer extends Component {
constructor(props) {
super(props);
this.state = {
isRunning: false,
secondsElapsed: 0
};
}
getHours() {
return ('0' + Math.floor(this.state.secondsElapsed / 3600)).slice(-2);
}
getMinutes() {
return ('0' + Math.floor(this.state.secondsElapsed / 60) % 60).slice(-2);
}
getSeconds() {
return ('0' + this.state.secondsElapsed % 60).slice(-2);
}
handleStopClick() {
clearInterval(this.incrementer);
}
componentDidMount() {
this.isRunning = true;
console.log(this.isRunning);
var _this = this; // reference to component instance
this.incrementer = setInterval( () => {
_this.setState({
secondsElapsed: (_this.state.secondsElapsed + 1)
});
}, 1000)
}
playOrPauseButton() {
if (this.isRunning) {return <PauseButton />}
else {return <PlayButton />}
}
render() {
return (
<div>
{this.playOrPauseButton()}
<StopButton /> <hr />
{this.getHours()} : {this.getMinutes()} : {this.getSeconds()}
</div>
);
}
}
export default Timer;
还有 StopButton.jsx:
import '../assets/css/App.css';
import React, { Component } from 'react';
import Timer from './Timer';
class StopButton extends Component {
handleClick () {
console.log('this is: ', this);
Timer.handleStopClick() // here's where I'd like to call Timer's function
}
render() {
return (
<button onClick={(e) => this.handleClick(e)}>
■
</button>
);
}
}
export default StopButton;
【问题讨论】: