ReactJSとElectronを使用してストップウォッチアプリを開発しています。私は時間を追跡し、時計&コントロールを表示するタイマーコンポーネントを持っています。Reactの他の無関係のコンポーネントから1つのコンポーネントの機能を呼び出す
コントロールは、再生、一時停止、停止の3つのボタンで構成されます。これらのButtonコンポーネントは、Timerコンポーネントとはまったく関係ありません。
私の質問は:TimerコンポーネントにhandleStopClick()
という関数がある場合、StopButtonコンポーネントから呼び出すにはどうすればいいですか?
注:再生/一時停止機能は現在ありません。 Timerはマウントされたときに開始され、1つのStopボタンでクリアされます。私はこれをソートしたときに残りを追加します。ここで
は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;
私は私のコンポーネントを持つ任意の親子関係を持っていないと思います。私の理解では、それらは単に2つの別々の.jsxファイルです。 'parentStopClick'は定義され、インスタンス化され、一度に値が割り当てられますか? –
Hmm ... Stopボタンをクリックすると 'Uncaught TypeError:this.props.parentStopClickは関数ではありません 'というエラーが表示されます –
親子関係は' Timer'内の 'StopButton'のレンダリングに由来しますどのように 'Timer'から小道具を渡すことができますか? 'StopButton'はES2015のクラス構文で書かれているので、インスタンス上で小道具を参照したい場合は、[constructor method](http://stackoverflow.com/a/34076378/7864431)で' super() 'を呼び出さなければなりません( 'this.props')。 –