【问题标题】:react-native-navigation navigator is undefined custom buttonreact-native-navigation navigator 是未定义的自定义按钮
【发布时间】:2018-05-09 06:11:58
【问题描述】:

我正在使用 Wix 的 React Native Navigation (https://github.com/wix/react-native-navigation)

我也在我的应用中使用 Redux。

我正在尝试向顶部栏添加自定义按钮,以便触发打开和关闭抽屉。

我正在向选项卡添加一个抽屉,如下所示:

Navigation.startTabBasedApp({
    tabs: [
      {
        label: 'Home',
        screen: 'swiftyApp.Home',
        icon: icons.homeOutline,
        selectedIcon: icons.home,
        title: 'Home',
        navigatorStyle,
        navigatorButtons: {
          leftButtons: [
            {
              id: 'custom-button',
              component: 'CustomButton',
              passProps: {
                text: 'Hi!'
              }
            }
          ]
        }
      }
    ],
    drawer: {
      left: {
        screen: 'swiftyApp.Drawer',
        passProps: {}
      },
      style: {
        drawerShadow: false,
        contentOverlayColor: 'rgba(0,0,0,0.25)',
        leftDrawerWidth: 75,
        rightDrawerWidth: 25
      },
      type: 'MMDrawer',
      animationType: 'slide',

      disableOpenGesture: false
    },
    appStyle: {
      orientation: 'portrait',
      hideBackButtonTitle: true
    }
  });
});

我的自定义按钮组件看起来像

const CustomButton = props => {
  console.log(props);
  const { text, navigator } = props;
  return (
    <TouchableOpacity
      style={[styles.button, { backgroundColor: 'tomato' }]}
      onPress={() =>
        navigator.toggleDrawer({
          side: 'left',
          animated: true
        })
      }
    >
      <View style={styles.button}>
        <Text style={{ color: 'white' }}>{text}</Text>
      </View>
    </TouchableOpacity>
  );
};

按预期显示按钮并应用样式。但是,当单击按钮时,由于未定义 navigator.toggleDrawer 会引发 onPress 失败的异常,在检查传入的导航器道具的输出时,我可以在日志中看到:

2017-11-25 13:33:48.703 [info][tid:com.facebook.react.JavaScript] '************', { testID: 'CustomButton',
  navigator: undefined,
  passPropsKey: 'customButtonComponent3',
  rootTag: 21,
  text: 'Hi!' }

Navigator 确实是未定义的。我一辈子都说不出来为什么。

如何将导航器传递给导航栏的自定义按钮,以便打开抽屉或触发模式?

【问题讨论】:

    标签: javascript react-native-navigation velo


    【解决方案1】:

    自定义按钮不与导航器关联。您需要在屏幕的构造函数中设置按钮,并在 props 中传递导航器。

    constructor(props) {
        super(props);
        this.props.navigator.setButtons(this.navigatorButtons(this.props.navigator));
      }
    
      navigatorButtons = (navigator) => {
        return {
          leftButtons: [
            {
              id: 'custom-button',
              component: 'CustomButton',
              passProps: {
                text: 'Hi!',
                navigator
              }
            }
          ]
        };
      }
    

    别忘了,Android 不支持自定义左键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多