如何使用React Native创建倒计时器

如何使用React Native创建倒计时器

我们的主要目标是构建一个简单易用的倒计时器,它能以年、日、小时、分钟和秒的形式展示距离特定日期的剩余时间。

要设置开发环境,请先安装Node.js。然后使用Expo CLI版来无缝运行React Native应用程序。Expo是一个基于JavaScript和React的平台,用于创建iOS、Android和Web环境的跨平台移动应用程序。它提供了一系列工具和服务,有效地简化了整个开发过程。

先决条件

  • React Native介绍
  • React Native组件
  • Expo CLI
  • Node.js和npm(Node Package Manager)

创建React Native应用程序的步骤

步骤1: 使用以下命令创建一个React Native应用程序

npx create-expo-app CountdownTimerApp

步骤2: 创建项目文件夹后,即 CountdownTimerApp,使用以下命令进行导航

cd CountdownTimerApp

项目结构

如何使用React Native创建倒计时器

方法

在这个方法中,我们将使用react-native-modal-datetime-picker库来启用日期和时间的选择。在启动时,应用程序设置一个默认的倒计时日期和时间,然后根据年、天、小时、分钟和秒的剩余时间进行计算,并以美观的格式显示。用户可以通过按下标注为“开始计时器”和“重置计时器”的专用按钮来轻松地启动或重置倒计时。倒计时完成后,计时器会自动重置。

要安装react-native-modal-datetime-picker库,请使用以下命令:

npm install react-native-modal-datetime-picker

示例: 在这个示例中,我们将使用上面解释的方法

// App.js 
  
import React, { useState, useEffect } from "react"; 
import { 
    SafeAreaView, 
    StyleSheet, 
    Text, 
    View, 
    Button, 
} from "react-native"; 
import DateTimePickerModal from "react-native-modal-datetime-picker"; 
  
const App = () => { 
    const [isDatePickerVisible, setDatePickerVisible] = 
        useState(false); 
    const [expiryDate, setExpiryDate] = useState( 
        new Date() 
    ); // Default to current date and time 
    const [timeUnits, setTimeUnits] = useState({ 
        years: 0, 
        days: 0, 
        hours: 0, 
        minutes: 0, 
        seconds: 0, 
    }); 
  
    useEffect(() => { 
        const calculateTimeUnits = (timeDifference) => { 
            const seconds = Math.floor( 
                timeDifference / 1000 
            ); 
            setTimeUnits({ 
                years: Math.floor( 
                    seconds / (365 * 24 * 60 * 60) 
                ), 
                days: Math.floor( 
                    (seconds % (365 * 24 * 60 * 60)) / 
                        (24 * 60 * 60) 
                ), 
                hours: Math.floor( 
                    (seconds % (24 * 60 * 60)) / (60 * 60) 
                ), 
                minutes: Math.floor( 
                    (seconds % (60 * 60)) / 60 
                ), 
                seconds: seconds % 60, 
            }); 
        }; 
  
        const updateCountdown = () => { 
            const currentDate = new Date().getTime(); 
            const expiryTime = expiryDate.getTime(); 
            const timeDifference = expiryTime - currentDate; 
  
            if (timeDifference <= 0) { 
                // Countdown finished 
                calculateTimeUnits(0); 
            } else { 
                calculateTimeUnits(timeDifference); 
            } 
        }; 
  
        updateCountdown(); 
        const interval = setInterval(updateCountdown, 1000); 
  
        return () => clearInterval(interval); 
    }, [expiryDate]); 
  
    const formatTime = (time) => { 
        return time.toString().padStart(2, "0"); 
    }; 
  
    const handleStartTimer = () => { 
        setDatePickerVisible(true); 
    }; 
  
    const handleResetTimer = () => { 
        setExpiryDate(new Date()); // Reset to current date and time 
    }; 
  
    const handleDateConfirm = (date) => { 
        setExpiryDate(date); 
        setDatePickerVisible(false); 
    }; 
  
    const handleDateCancel = () => { 
        setDatePickerVisible(false); 
    }; 
  
    return ( 
        <SafeAreaView style={styles.container}> 
            <View style={styles.container}> 
                <Text style={styles.title}> 
                    Geeksforgeeks 
                </Text> 
                <Text style={styles.subtitle}> 
                    React Native Countdown Timer 
                </Text> 
                <View style={styles.timer}> 
                    <Text 
                        style={[ 
                            styles.timeUnit, 
                            styles.yearUnit, 
                        ]} 
                    > 
                        {formatTime(timeUnits.years)} 
                    </Text> 
                    <Text 
                        style={styles.timeSeparator} 
                    ></Text> 
                    <Text 
                        style={[ 
                            styles.timeUnit, 
                            styles.dayUnit, 
                        ]} 
                    > 
                        {formatTime(timeUnits.days)} 
                    </Text> 
                    <Text 
                        style={styles.timeSeparator} 
                    ></Text> 
                    <Text 
                        style={[ 
                            styles.timeUnit, 
                            styles.hourUnit, 
                        ]} 
                    > 
                        {formatTime(timeUnits.hours)} 
                    </Text> 
                    <Text 
                        style={styles.timeSeparator} 
                    ></Text> 
                    <Text 
                        style={[ 
                            styles.timeUnit, 
                            styles.minuteUnit, 
                        ]} 
                    > 
                        {formatTime(timeUnits.minutes)} 
                    </Text> 
                    <Text 
                        style={styles.timeSeparator} 
                    ></Text> 
                    <Text 
                        style={[ 
                            styles.timeUnit, 
                            styles.secondUnit, 
                        ]} 
                    > 
                        {formatTime(timeUnits.seconds)} 
                    </Text> 
                    <Text 
                        style={styles.timeSeparator} 
                    ></Text> 
                </View> 
                <Text style={styles.timetitle}> 
                    Years Days Hours Minutes Seconds 
                </Text> 
                <View style={styles.buttonContainer}> 
                    <Button 
                        title="Start Timer"
                        onPress={handleStartTimer} 
                        style={styles.button} 
                    /> 
                    <Button 
                        title="Reset Timer"
                        onPress={handleResetTimer} 
                        style={[ 
                            styles.button, 
                            styles.resetButton, 
                        ]} 
                    /> 
                </View> 
  
                <DateTimePickerModal 
                    isVisible={isDatePickerVisible} 
                    mode="datetime"
                    onConfirm={handleDateConfirm} 
                    onCancel={handleDateCancel} 
                /> 
            </View> 
        </SafeAreaView> 
    ); 
}; 
  
const styles = StyleSheet.create({ 
    container: { 
        flex: 1, 
        padding: 20, 
        justifyContent: "center", 
        alignItems: "center", 
        backgroundColor: "#f0f0f0", 
    }, 
    title: { 
        fontSize: 30, 
        fontWeight: "bold", 
        paddingVertical: 20, 
        color: "green", 
    }, 
    subtitle: { 
        marginBottom: 20, 
        fontSize: 18, 
    }, 
    timer: { 
        flexDirection: "row", 
        alignItems: "center", 
    }, 
    timeUnit: { 
        fontSize: 24, 
        fontWeight: "bold", 
        paddingHorizontal: 10, 
        paddingVertical: 5, 
    }, 
    yearUnit: { 
        backgroundColor: "red", 
        borderRadius: 15, 
        color: "white", 
    }, 
    dayUnit: { 
        backgroundColor: "#3498db", 
        borderRadius: 15, 
        color: "white", 
    }, 
    hourUnit: { 
        backgroundColor: "#27ae60", 
        borderRadius: 15, 
        color: "white", 
    }, 
    minuteUnit: { 
        backgroundColor: "#f39c12", 
        borderRadius: 15, 
        color: "white", 
    }, 
    secondUnit: { 
        backgroundColor: "#9b59b6", 
        borderRadius: 15, 
        color: "white", 
    }, 
    timeSeparator: { 
        fontSize: 24, 
        fontWeight: "bold", 
        marginHorizontal: 5, 
    }, 
    timetitle: { 
        fontSize: 17, 
        padding: 10, 
        paddingRight: 19, 
        fontWeight: "bold", 
    }, 
}); 
  
export default App;

步骤3:要运行React Native应用程序,请打开终端并输入以下命令。

npx expo start
  • 在Android上运行:
npx react-native run-android
  • 在Ios上运行:
npx react-native run-ios

输出:

如何使用React Native创建倒计时器

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程