React Native CountDown — 让计时更加优雅
import React, { Component } from 'react';
import { Text, TouchableOpacity } from 'react-native';
class CountDown extends Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
this.interval = null;
}
componentDidMount() {
this.startCountDown();
}
componentWillUnmount() {
this.clearCountDown();
}
startCountDown = () => {
const { seconds } = this.props;
this.interval = setInterval(() => {
if (seconds > 0) {
this.setState({ seconds: seconds - 1 });
} else {
this.clearCountDown();
}
}, 1000);
}
clearCountDown = () => {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
}
render() {
const { seconds } = this.state;
const { onTimeout } = this.props;
return (
<TouchableOpacity onPress={onTimeout}>
<Text>{seconds}秒</Text>
</TouchableOpacity>
);
}
}
CountDown.defaultProps = {
seconds: 60,
onTimeout: () => {},
};
export default CountDown;
这段代码实现了一个简单的计时器组件,当组件挂载时开始计时,计时完毕或组件卸载时清除计时器。这个例子展示了如何在React Native应用中处理计时器逻辑,并且遵循了组件的生命周期,使得代码更易于理解和维护。
评论已关闭