React Native中点击按钮(onPress)时如何显示日期和时间?
React Native点击按钮显示当前日期时间的实现方案
你的代码存在几个关键问题,导致点击按钮无法正确显示时间,以下是修正后的实现:
修正后的完整代码
import { useState } from 'react'; import { StyleSheet, Text, View, Button } from 'react-native'; export default function App() { const [currentdate, setCurrentdate] = useState(''); // 封装生成当前日期时间的函数 const getCurrentDateTime = () => { const now = new Date(); const date = now.getDate(); const month = now.getMonth() + 1; const year = now.getFullYear(); const hours = now.getHours(); const min = now.getMinutes(); const sec = now.getSeconds(); // 格式化时间字符串 return `${date}/${month}/${year} ${hours}:${min}:${sec}`; }; return ( <View style={styles.container}> <Text>Showing current date and time</Text> {/* 显示当前时间的文本组件 */} {currentdate && <Text style={styles.date}>{currentdate}</Text>} <Button title='hit me' onPress={() => setCurrentdate(getCurrentDateTime())} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, date: { fontSize: 35, marginTop: 30, paddingHorizontal: 30, borderWidth: 2, borderColor: 'black', color: 'blue' } });
关键修改说明
- 移除多余的
useEffect:原useEffect会在组件挂载时自动生成时间,但需求是点击按钮才触发,因此不需要这个自动执行的逻辑。如果需要组件初始化时就显示时间,可以在useState里直接调用getCurrentDateTime(),或者保留空依赖的useEffect调用该函数。 - 封装时间生成函数:把获取和格式化日期时间的逻辑抽成独立函数,让代码更清晰,也方便复用。
- 修正
onPress逻辑:原代码在onPress里直接返回Text组件是错误的,正确的做法是调用setCurrentdate更新状态,React会自动根据新状态重新渲染视图。 - 条件渲染时间文本:通过
{currentdate && ...}实现点击按钮后才显示时间文本,初始状态下不显示。
内容的提问来源于stack exchange,提问作者Supolaris
相关产品推荐
相关产品推荐

