在 React Native 中浏览屏幕时显示 activity 指示符

Show activity indicator while navigating through screens in React Native

我有一个名为 ScreenOne.js 的文件。我的目标是在从 ScreenOne 导航到 ScreenTwo 时显示 activity 指示器三秒钟。所以流程是: ScreenOne -> Activity 指示器(显示三秒) -> ScreenTwo。 这就是我想要展示的内容:

<ActivityIndicator color={blue} size="large" />

我已经尝试了几种方法,ScreenOne 文件包含指标的 startLoading 函数。非常感谢您对此的帮助。 这是 ScreenOne 文件:

const ScreenOne = () => {
  const navigation = useNavigation();

  const navigateTo = () => {
    navigation.navigate('ScreenTwo')
  }

  const [loading, setLoading] = useState(false);

  const startLoading = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 3000);
  };

  return (
    <ScreenContainer>
      <Header style={styles.header} >
        <Text style={styles.textHeader} >ScreenOne</Text>
      </Header>
      <Text style={styles.message} >This is the ScreenOne</Text>
      <Button rounded buttonText='Go to ScreenTwo' textColor={colors.white} onPress={navigateTo} />
    </ScreenContainer>
  )
}

export default ScreenOne

我想你想要这样的东西

Working Example Here

import * as React from 'react';
import { Button, View, ActivityIndicator, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

function ScreenOne({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>This is ScreenOne</Text>
      <Button
        title="Go to ScreenTwo"
        onPress={() => navigation.navigate('ScreenTwo')}
      />
    </View>
  );
}

function ScreenTwo({ navigation }) {
  const [Loading, SetLoading] = React.useState(true);

  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      SetLoading(true);
      setTimeout(() => {
        SetLoading(false);
      }, 3000);
    });

    return unsubscribe;
  }, [navigation]);

  if (Loading) {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <ActivityIndicator color={'blue'} size="large" />
      </View>
    );
  }

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>This is ScreenTwo</Text>
      <Button title="Go back" onPress={() => navigation.goBack()} />
    </View>
  );
}

const Stack = createStackNavigator();

function MyStack() {
  return (
    <Stack.Navigator screenOptions={{ headerShown: false }}>
      <Stack.Screen name="ScreenOne" component={ScreenOne} />
      <Stack.Screen name="ScreenTwo" component={ScreenTwo} />
    </Stack.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <MyStack />
    </NavigationContainer>
  );
}