推送屏幕上未定义的 React Native Navigation 道具

React Native Navigation props undefined on pushed screen

我是 React Native 的新手,我遵循了 React Native 的身份验证流程教程。现在我正在使用打字稿,我认为这与它有关。因为当我只是复制 javascript 示例时它起作用了。

export default class SignInScreen extends Component<NavigationScreenProps> {

    constructor(props: NavigationScreenProps) {
        super(props);
    }

    render() {
        return (
            <View style={styles.container}>
                <Text>Sign in</Text>
                <Button title="Sign in!" onPress={this.signIn}/>
            </View>
        );
    }

    private async signIn() {
        //await AsyncStorage.setItem('userToken', 'abc');
        console.log("PROPS", this.props);
        this.props.navigation.navigate('App');
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

AuthLoadingScreen

export default class AuthLoadingScreen extends Component<NavigationScreenProps> {

    constructor(props: NavigationScreenProps) {
        super(props);
        this.bootstrap();
    }

    private async bootstrap() {
        console.log("AUTH props", this.props);
        try {
        const userToken = await AsyncStorage.getItem('userToken');
        this.props.navigation.navigate(userToken ? 'App' : 'Auth');
        } catch (err) {
            console.log('Error', err.message);
        }
    }

    render() {
        return (
            <View>
                <ActivityIndicator />
                <StatusBar barStyle="default" />
            </View>
        );
    }
}

App.tsx

const AppStack = createBottomTabNavigator({
  Home: HomeScreen,
  Settings: SettingsScreen,
});
const AuthStack = createStackNavigator({ SignIn: SignInScreen });

export default createAppContainer(createSwitchNavigator(
  {
    AuthLoading: AuthLoadingScreen,
    App: AppStack,
    Auth: AuthStack,
  },
  {
    initialRouteName: 'AuthLoading',
  }
));

现在在 AuthLoadingScreen 上,道具不是未定义的,我推送到 SignInScreen,但是当我点击按钮时,道具是未定义的。我不知道为什么,因为我找到的所有示例都是这样做的?

那是因为 this 不在您期望的上下文中。该函数是无界的,因此 this 不包含 props。绑定方法如下:

<Button title="Sign in!" onPress={this.signIn.bind(this)}/>

您还可以使用以下内容,无需 binding:

<Button title="Sign in!" onPress={() => { this.signIn() }}/>

虽然我更喜欢第一个例子