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

た 入场券 2022-03-22 13:40 192阅读 0赞

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

  1. static navigationOptions = (
  2. (props) => {
  3. return {
  4. headerBackTitle: null,
  5. headerRight: (
  6. <TouchableOpacity onPress={this.actionSheetTest}>
  7. <Image style={Styles.profileMarginRight20} source={require('../../../../img/threePoints.png')} />
  8. </TouchableOpacity>
  9. )
  10. }
  11. }
  12. )

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

  1. actionSheetTest = () => {
  2. ActionSheet.show(
  3. {
  4. options: ['举报', '取消'],
  5. cancelButtonIndex: 1,
  6. destructiveButtonIndex: 0
  7. },
  8. buttonIndex => {
  9. console.log(buttonIndex)
  10. if (buttonIndex === 0) {
  11. console.log('动态:' + this.props.navigation.getParam('postId', '') + '被举报')
  12. }
  13. }
  14. )
  15. }

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

  1. onPress={this.actionSheetTest}>

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

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

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

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

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

  1. static navigationOptions = (
  2. (props) => {
  3. return {
  4. headerBackTitle: null,
  5. headerRight: (
  6. <TouchableOpacity onPress={props.navigation.state.params.openActionSheet}>
  7. <Image style={Styles.profileMarginRight20} source={require('../../../../img/threePoints.png')} />
  8. </TouchableOpacity>
  9. )
  10. }
  11. }
  12. )

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

发表评论

表情:
评论列表 (有 0 条评论,192人围观)

还没有评论,来说两句吧...

相关阅读