React-Native使用React-Navigation在顶部导航栏调用外部定义函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sun_DongLiang/article/details/86679453

背景:
最近在开发项目时需要在导航栏中点击菜单按钮之后弹出来相应的动态的举报确认。但是举报确认的ActionSheet是在外部调用的。
上图:
1: 点击导航栏中的菜单选项(右上角)
在这里插入图片描述
2:弹出来相应的举报选项
在这里插入图片描述
接下来就走一遍这个流程。并将逻辑理清楚。
在项目中是使用react-navigation进行导航的。因此这个事件的触发必须要放在navigationOptions中进行定义。在前一篇博客里,描述了如何在导航栏中进行跳转。在这一部分还是使用到了相应的知识点。
看一下代码:
1: 这是定义的navigationOptions,点击时触发外部定义的actionSheetTest函数。关于这一部分的知识点可以看上一篇的博客,有相应的解释

static navigationOptions = (
    (props) => {
      return {
        headerBackTitle: null,
        headerRight: (
          <TouchableOpacity onPress={this.actionSheetTest}>
            <Image style={Styles.profileMarginRight20} source={require('../../../../img/threePoints.png')} />
          </TouchableOpacity>
        )
      }
    }
  )

2: 下面的代码是相应的外部定义函数actionSheet

actionSheetTest = () => {
    ActionSheet.show(
      {
        options: ['举报', '取消'],
        cancelButtonIndex: 1,
        destructiveButtonIndex: 0
      },
      buttonIndex => {
        console.log(buttonIndex)
        if (buttonIndex === 0) {
          console.log('动态:' + this.props.navigation.getParam('postId', '') + '被举报')
        }
      }
    )
  }

简单的解释一下:
关于ActionSheet的使用可以去NativeBase的官网去看一下简单的demo,比较详细。
需要注意的一点:<Root>组件
在这里插入图片描述
为了保证ActionSheet的正常使用,必须引入Root组件,并将你的最顶层的组件包裹在Root组件中。
ActionSheet.show()内部有一个箭头函数传入buttonIndex,当点击的是举报时。就会输出相应的动态ID被举报。
可是想的简单,在navigationOptions中他是无法调用这个函数的

onPress={this.actionSheetTest}>

onPress回调是不能成功执行的。
分析:
如果看过上一篇博客,你就会发现传入navigationOptions中的是props,因此你用onPress={this.actionSheetTest}>是找不到这个函数的。因此,我们需要在传入的props上做点文章。
上代码:

componentDidMount () {
    this.props.navigation.setParams({ openActionSheet: this.actionSheetTest })
  }

在组件渲染之后为navigation设置params,自定义一个function,在这里调用外部函数,actionSheetTest将这个函数赋给参数:openActionSheet。这样我们在项目中console一下navigation以及他对应的函数看看有什么变化。

      <TouchableOpacity onPress={() => console.log(props.navigation)}>
            <Image style={Styles.profileMarginRight20} source={require('../../../../img/threePoints.png')} />
      </TouchableOpacity>

结果为:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
此时我们通过对navigation中的params的操作就可以在navigationOptions中获取到相应的函数了。此时调用已经毫无阻拦了。

static navigationOptions = (
    (props) => {
      return {
        headerBackTitle: null,
        headerRight: (
          <TouchableOpacity onPress={props.navigation.state.params.openActionSheet}>
            <Image style={Styles.profileMarginRight20} source={require('../../../../img/threePoints.png')} />
          </TouchableOpacity>
        )
      }
    }
  )

总结:
由navigationOptions中只能接收props,因此考虑在props中的navigation中搞点事情。所以在生命周期函数中将自定义函数setParams一下赋值给navigation中的自定义参数。这样在navigationOptions中就可以调用相应的函数了。
灵感借鉴:
https://stackoverflow.com/questions/53263368/react-native-cannot-read-property-root-of-undefined-when-using-nativebase-d
谢谢!!!

猜你喜欢

转载自blog.csdn.net/sun_DongLiang/article/details/86679453