在推送的屏幕上反应未定义的本机导航道具

时间:2019-06-04 13:33:40

标签: typescript react-native react-native-navigation

我是React Native的新手,我按照React Native的Authentication Flow教程学习。现在我正在使用打字稿,我认为这与它有关。因为当我只复制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,但是当我单击按钮时,道具是未定义的。我不知道为什么,因为我发现的所有示例都是这样做的?

1 个答案:

答案 0 :(得分:1)

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

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

您也可以使用以下内容,而无需bind

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

尽管我更喜欢第一个示例。