LoginSignup
3
1

More than 5 years have passed since last update.

ReactNavigationのDrawerNavigatorから直接メソッドを実行する方法

Last updated at Posted at 2018-10-28

結論から言うと「直接メソッドは実行できない」ようです。

contentComponentを利用してItem項目にButtonなどを差し込み、そのonPress()等で対応するか、おとなしく一度Component(画面)を経由するしかないようです(今回は前者の対応です)。

やりたいことはDrawerにLogoutを仕込み、そのままLogoutしたいだけなのですが。。。

以下、Drawerの定義を抜粋したコード。
ButtonだとStyleが限定されるのでTextで対応しました。また、既存のメニューと似せるためには強引にstyleで合わせる必要があります。
なので、sytleに関する記述はかなりHack的になり環境依存です。もっとまともな方法があれば教えてほしい。。。

Viewだと改行がはいるのでTextで囲ったり、Textだとmarginが効かないのでViewで囲ったりと・・・。私が不慣れなだけですが。

.....
//drawer
export const Drawer = createDrawerNavigator(
  {
    Stacks: {
      screen: Stack,
      navigationOptions: {
        drawerIcon: <Icon name="check" size={24} />
      }
    },
    Tabs: {
      screen: Tab,
      navigationOptions: {
        drawerIcon: <Icon name="check" size={24} />
      }
    },
    Single1: {
      screen: createStackNavigator({
        Single1: { screen: Single1 }
      }),
      navigationOptions: {
        drawerIcon: <Icon name="check" size={24} />
      }
    },
    Single2: {
      screen: Single2,
      navigationOptions: {
        drawerIcon: <Icon name="check" size={24} />
      }
    },
  },
  {
    contentComponent: (props) => (
      <View style={{ flex: 1, marginTop: 40 }}>
        <SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
          <DrawerItems {...props} />
          {/* <Button
            title="Logout"
            onPress={()=>alert('hoge')}
          /> */}
          <Text>
            <View style={{ paddingTop:10, width: 60, height: 47, alignItems: 'center'}}>
              <Icon name="check" size={24} color={'#666'} />
            </View>
            <View style={{ width: 80, height: 47, justifyContent:'center'}}>
              <Text
                style={{ marginLeft: 12, fontWeight: '700', color: '#111'}}
                onPress={() => props.navigation.navigate('Single1')}
              >Logout
              </Text>
            </View>
          </Text>
        </SafeAreaView>
      </View>
    ),
  }
);
.....

結果

一番下の[Logout]は偽装したものです。。。push時の動作とか違うけど、まあ、Logoutなら押したっきり移動するのでなんとか許容できる範囲かな・・・。

スクリーンショット 2018-10-29 6.38.39.png

参考

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1