【问题标题】:How can I replace screen with React Navigation for React Native如何用 React Native 的 React Navigation 替换屏幕
【发布时间】:2017-12-31 17:48:21
【问题描述】:

如何用 React Native 的 React Navigation 替换屏幕

现在我是一个新手,我无法理解 getStateForAction 现在我在屏幕 1 上有参数并导航到屏幕 2,并通过基本的参数用户名导航到堆栈上的嵌套屏幕 1 > 2

但我需要在屏幕 2 处于活动状态后将屏幕 1 替换为屏幕 2(在路由器通量上替换为 ActionConst.REPLACE)并以新方式发送参数

谁能指导我谢谢。



屏幕 1

  onPress = () => {

          this.props.navigation.navigate('Sc2', {username: this.state.username});

  }


屏幕 2

componentWillMount() {

const {state} = this.props.navigation;
console.log(state.params.username);

}

---------------

路由器

export const LoginNavStack = StackNavigator({
  Sc1: {
    screen: Sc1
  },
  Sc2: {
   screen: Sc2,
 },

});

【问题讨论】:

    标签: javascript reactjs react-native react-router


    【解决方案1】:

    你可以使用navigation.replace

    使用

    this.props.navigation.replace('Sc2');
    

    代替

    this.props.navigation.navigate('Sc2', {username: this.state.username});
    

    您可以从这里找到更多信息https://reactnavigation.org/docs/en/navigation-key.html

    【讨论】:

    • 我们如何在 Typescript 中使用替换?我明白了Property 'replace' does not exist on type 'NavigationProp<Record<string, object | undefined>, string, NavigationState, {}, {}>'.ts(2339)
    • 在使用 navigation.replace 时如何将任何信息传递到其他屏幕??
    【解决方案2】:

    用这个代替navigation.replace

    navigation.reset({
     index: 0,
     routes: [{ name: 'Profile' }],
     });
    

    【讨论】:

    • navigation.reset() 的重要说明,它将清除您的导航堆栈并用新屏幕替换它。当您仍需要保留一些导航历史记录时,这可能不是您想要的行为。例如:Navigation stack: Home -> Profile -> Settings 如果您在设置屏幕中调用 reset 并通过配置文件,堆栈将如下所示 New Navigation stack: Profile 问题是当您要导航回主页时,它将关闭应用程序,因为没有以前的堆栈中的屏幕
    • 这在 react-navigation 6 中对我有用,const navigation = useNavigation<NavigationProp<SomeStackParamList>>()。
    【解决方案3】:

    “替换”仅在堆栈导航中可用

    替换输入:

    import { useNavigation } from '@react-navigation/core'
    import { StackNavigationProp } from '@react-navigation/stack'
    
    type YourNavigatorParamList = {
      CurrentScreen: undefined
      DifferentScreen: { username: string }
    }
    
    const navigation = useNavigation<StackNavigationProp<YourNavigatorParamList, 'CurrentScreen'>>()
    
    navigation.replace('DifferentScreen', { username: 'user01' })

    https://reactnavigation.org/docs/navigation-prop/#navigator-dependent-functions https://reactnavigation.org/docs/typescript#annotating-usenavigation

    【讨论】:

      【解决方案4】:

      如果有人还在研究如何在 React Native 中替换屏幕并且正在使用 react-navigation,这里是:

      import { StackActions } from '@react-navigation/native';
      
      navigation.dispatch(
        StackActions.replace('Profile', {
          user: 'jane',
        })
      );
      

      更多信息请参考:https://reactnavigation.org/docs/stack-actions/#replace

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        • 2023-04-09
        • 2020-06-29
        • 1970-01-01
        • 1970-01-01
        • 2020-04-20
        • 1970-01-01
        相关资源
        最近更新 更多