简体   繁体   English

如何使用反应导航从标题中的按钮“导航”到新屏幕?

[英]How to `navigate` to new screen from button in header with react-navigation?

I'm using react-navigation and want to add a button to the right on my header that will navigate to a different screen.我正在使用react-navigation并希望在我的标题右侧添加一个按钮,该按钮将导航到不同的屏幕。 But when setting up the navigationOptions , I'm wondering how I can get access to the navigate function in the callback that is invoked when the button is pressed:但是在设置navigationOptions ,我想知道如何在按下按钮时调用的回调中访问navigate功能:

const RootNavigationStack = StackNavigator({
  PokemonList: {
    screen: PokemonListWrapper,
    navigationOptions: {
      title: ({state}) => `Pokedex`,
      header: ({ state, setParams }) => {
        return {
          visible: true,
          right: (
            <Button
              title={'Add'}
              onPress={() => // navigate to new screen here
            />
          ),
        }
      }
    },
  },
, {
  headerMode: 'screen'
})

Any ideas how this can be achieved?任何想法如何实现? I was thinking of maybe using withNavigation , but am still not quite clear on how that would work.我正在考虑使用withNavigation ,但我仍然不太清楚它是如何工作的。

The other answer works in older versions of react Navigation.另一个答案适用于旧版本的 react Navigation。

For new versions, try this:对于新版本,试试这个:

static navigationOptions = ({ navigation }) => ({
        headerRight: (
            <Button 
                title='Setting' 
                onPress={ () => navigation.navigate('RouteName') }                
                backgroundColor= "rgba(0,0,0,0)"
                color="rgba(0,122,255,1)"
            />
        )});

I solved the same problem using this(inside Screen/Component Class )我使用这个解决了同样的问题(在 Screen/Component Class 中)

static navigationOptions = ({navigation}) => {
  return {
    title: 'Next',
    headerRight: <Button
                     title="Next"

                     onPress={ () => navigation.navigate('RegPasswordScreen')} />

  };
};

Try this.尝试这个。

    header: ({ navigate }) => ({
       right: (
          <Button onPress={() => navigate('screen2')}  />
       )
    }),

In latest version, you can do this by hooks.在最新版本中,你可以通过钩子来做到这一点。

import { useNavigation } from '@react-navigation/native';

const CustomHeaderComponent = (props) => {
  const navigation = useNavigation();
  return <Button onPress={() => navigation.navigate('screen2')} />;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM