Currently, I am developing a react native application that incorporates a timer component which I have created with the following code:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
TouchableOpacity,
View
} from 'react-native';
import styles from '../styles/style';
export default class Timer extends Component<{}> {
constructor(props) {
super();
this.state = {
time: 10,
timerStarted: false
}
}
startTimer() {
this.interval = setInterval(() => {
this.setState({
isFirstRender: !this.state.isFirstRender,
time: this.state.time-1,
isTimerRunning: true
});
}, 1000);
}
render() {
if (!this.state.isTimerRunning)
this.startTimer();
return (
<View style={styles.scoreBoard}>
<Text style={styles.timerText}>Time: {this.state.time}</Text>
</View>
);
}
}
In this component, there is a state variable called time that decreases from 10 in intervals of one second. In order to alert the calling component when the timer reaches zero, I need to implement a notification system. The primary JavaScript file in my program is App.js, which instantiates the timer within its render function as shown below:
render () {
return (
<View style={{flex: 1, flexDirection: 'row'}}>
<View style={{flex: 1}}>
{/*This below is the component I need to return a value to this main class we are in*/}
<MyTimer />
</View>
</View>
);
}
I aim for the Timer class to send back some data, potentially a boolean, to notify the main class when the countdown ends. One approach could be passing a member function from the main class to the Timer class as a prop, although I am unsure if this method is correct. I have experimented with different strategies but leveraging props to transmit information to a component is straightforward, yet retrieving data proves to be challenging. Any guidance on achieving this would be appreciated. Thank you.