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

How to pass a function as a prop in React-Native

我目前正在使用 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 is not a function and its not defined.

你可以做的是 import { DrawerActions } from 'react-navigation-drawer' 并按照 docs.

中的说明使用它
this.props.navigation.dispatch(DrawerActions.toggleDrawer());

还要确保您的组件在导航内。