Javascript react native:当进入页面时,如何自动显示当前时间?
当进入页面时,如何自动显示当前时间? 当我到达Javascript react native:当进入页面时,如何自动显示当前时间?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,当进入页面时,如何自动显示当前时间? 当我到达NetuneyDigum页面时,我尝试显示当前时间, 在我的代码中,当前时间仅在我按下TouchableOpacityonpress时显示,并且我希望在用户到达页面时自动显示当前时间 function NetuneyDigum() { const navigation = useNavigation(); const [currentTime, setCurrentTime] = useState(''); const [isSelect
NetuneyDigum
页面时,我尝试显示当前时间,
在我的代码中,当前时间仅在我按下TouchableOpacity
onpress时显示,并且我希望在用户到达页面时自动显示当前时间
function NetuneyDigum() {
const navigation = useNavigation();
const [currentTime, setCurrentTime] = useState('');
const [isSelected, setSelection] = useState(false);
const [selectedValue, setSelectedValue] = useState('1');
return (
<>
<KeyboardAwareScrollView
style={{ flex: 1, backgroundColor: '#cbced4', marginBottom: 50 }}
>
<View
style={{
flex: 1,
alignItems: 'center',
backgroundColor: '#cbced4',
}}
>
<View
style={{
paddingTop: 30,
flexDirection: 'row',
paddingRight: 180,
}}
>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
left: 58,
}}
>
<Text
style={{
fontWeight: 'bold',
fontSize: 18,
color: 'black',
}}
>
current time:
</Text>
</View>
<View
style={{
width: 150,
borderRadius: 5,
borderColor: 'black',
borderWidth: 2,
left: 80,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'white',
}}
>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: 'black',
}}
>
{currentTime}
</Text>
</View>
<TouchableOpacity
onPress={() => {
const time = moment().format('HH:mm');
setCurrentTime(time);
}}
style={{
height: 60,
width: 60,
borderRadius: 5,
borderColor: 'black',
borderWidth: 2,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#275d9f',
left: 100,
}}
>
<Icon size={40} color="white" name="time-outline" />
</TouchableOpacity>
</View>
函数NetuneyDigum(){
const navigation=useNavigation();
常量[currentTime,setCurrentTime]=使用状态(“”);
const[isSelected,setSelection]=useState(false);
常量[selectedValue,setSelectedValue]=useState('1');
返回(
当前时间:
{currentTime}
{
常量时间=力矩().格式('HH:mm');
setCurrentTime(时间);
}}
风格={{
身高:60,
宽度:60,
边界半径:5,
边框颜色:“黑色”,
边界宽度:2,
对齐项目:“居中”,
为内容辩护:“中心”,
背景颜色:“#275d9f”,
左:100,,
}}
>
试试这种方法
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
const time = moment().format('HH:mm');
setCurrentTime(time);
});
这样试试
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
const time = moment().format('HH:mm');
setCurrentTime(time);
});
你可以这样使用它,它会自动来。之后,你可以改变时间显示
const[startedtime,setStartedtime]=useState(new Date());
您可以这样使用它,它将自动运行。之后,您可以更改时间显示
const[startedtime,setStartedtime]=useState(new Date());