I'm trying to create a simple stopwatch timer in React Native and I've created a new component called Chrono to handle the clock data(hours, minutes, etc.)
I'm triggering the clock count up on a button press in the following code:
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, AppRegistry, StyleSheet, Alert } from 'react-native';
import Chrono from './app/Chrono.js';
export default class morphX extends Component {
constructor(props) {
super(props)
this.state = {
randomCounter: 0
}
this.chrono = null
}
onItemPressed = () => {
this.chrono.startTimer()
}
updateRandomCounter = () => {
this.setState({
randomCounter: this.state.randomCounter + 1
})
}
clearCounter = () => {
this.setState({
randomCounter: 0
})
}
render() {
return (
<View style={styles.mainWrapper}>
<View style={styles.upperWrapper}>
<Chrono ref = { r => this.chrono = r} />
</View>
<View style={styles.bottomWrapper}>
<View style={styles.initialButtons}>
<TouchableOpacity
style={styles.touchableButton}
text="Let's Start!"
onPress={() => this.onItemPressed()}>
<Text style={styles.buttonTexts}>
Count Up!
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.touchableButton}
title="RESET!"
onPress={() => this.clearCounter()}>
<Text style={styles.buttonTexts}>
Reset!
</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
AppRegistry.registerComponent('morphX', () => morphX);
and the startTimer
is implemented in the Chrono.js
component here:
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, AppRegistry, StyleSheet, Alert } from 'react-native';
class Chrono extends Component {
constructor(props) {
super(props)
this.state = {
hours: 0,
minutes: 0,
seconds: 0
}
}
// Chronometer start function
startTimer = () => {
console.log(this)
this.setTimeout(function() {
console.log('HeY!')
this.setState({
seconds: 1
})
}, 1000);
}
// Chronometer pause function
pauseTimer = () => {
}
// Chronometer reset function
resetTimer = () => {
}
render() {
return (
<View style={styles.clockWrapper}>
<Text style={styles.hourWrapper}>
{this.state.hours}
</Text>
<Text style={styles.colonWrapper}>
:
</Text>
<Text style={styles.minuteWrapper}>
{this.state.minutes}
</Text>
<Text style={styles.colonWrapper}>
:
</Text>
<Text style={styles.secondsWrapper}>
{this.state.seconds}
</Text>
</View>
)
}
}
export default Chrono
I'm facing the error
this.setTimeout
is not a function
on the line where I'm calling the setTimeout
for some reason. Why?