如何在React-Native中将函数作为道具传递

时间:2019-09-13 12:51:02

标签: react-native navigation-drawer react-navigation expo

我目前正在React-Native中开发一个应用程序,其中包括DrawerNavigation,SwitchNavigation和AppContainer。我需要使用header.js中的一种方法来使抽屉起作用(toggleDrawer())

我尝试过在DrawerNavigator中传递该函数,但是没有用。

export default class Header extends React.Component {
render() {
return (
  <View style={styles.container}>
    <TouchableOpacity
      onPress={() => {
        this.props.navigation.toggleDrawer();
      }}
    >
      <Image
        source={require("/Users/Rron/AnketaApp/assets/hamburger- 
    icon.jpg")}
        style={styles.imageStyle}
      />
    </TouchableOpacity>
  </View>
        );
  }
  }
     });

 export default class HomeScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
   let drawerLabel = "Home";
  return { drawerLabel };
   };

   render() {
 return (
  <View style={styles.container}>
    <Header {...this.props}/>
    <ScrollView>
      <Content />
    </ScrollView>
  </View>
 );
 }
  }

  export default class DrawerNavigator extends React.Component {
   render() {
  return <AppContainer />;
    }
   }

     const AppDrawerNavigator = createDrawerNavigator(
       {
     Home: {
       screen: HomeScreen
    },
    Anketa: {
    screen: AnketaScreen
        }
      }
       );

       const AppContainer = createAppContainer(
      createSwitchNavigator({
         Introduction: {
           screen: IntroductionScreen
       },
         Drawer: {
       screen: AppDrawerNavigator``
            }
     })
      );

错误提示

  

this.props.navigation.toggleDrawer不是函数,也不是   定义。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以做的是import { DrawerActions } from 'react-navigation-drawer',并按照docs中的说明使用它。

this.props.navigation.dispatch(DrawerActions.toggleDrawer());

还要确保组件位于导航内。