【问题标题】:How to pass a function as a prop in React-Native如何在 React-Native 中将函数作为道具传递
【发布时间】:2023-03-28 04:37:01
【问题描述】:

我目前正在使用 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 不是函数,也不是 已定义。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 我使用了 this.props.navigation.dispatch(DrawerActions.toggleDrawer());安装 this.props.navigation.toggleDrawer();就像你说的,但现在弹出一个新错误:未定义不是对象(评估 reactNavigation:ThemeColor.light)
    • @kodak evaluating reactNavigation:ThemeColor.light 是另一个错误,可能不是来自您问题中的代码,请使用必要的代码更新您的问题。
    • 当你告诉我使用 this.props.navigation.dispatch(DrawerActions.toggleDrawer());这种方法而不是我的方法,所以与该错误相关的 dipatch 方法吗?
    • @kodak 如果您评论这两个部分,错误是否仍然存在?
    • 当我从 react-navigation-drawer 导入 DrawerAction 时才开始出现此错误,我注释了 dipatch 函数代码,但它仍然不断弹出。
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 2022-01-24
    • 1970-01-01
    • 2021-05-26
    • 2017-03-06
    • 2021-11-02
    • 2020-05-15
    相关资源
    最近更新 更多