React Native使用react-navigation时,设置navigationOptions中Static中使用this注意点

本文介绍了在React Navigation中如何正确地在静态配置中使用方法,避免`this`上下文丢失导致的问题,并提供了一种通过`navigation.setParams`传递方法的解决方案。

使用react-navigation时,单页面设置navigationOptions中,进行Static中调用方法,不能像以下设置

onPress = {()=>this.clickFinishButton()}
export default class extends Component {
  static navigationOptions = ({
    navigation,
    screenProps
  }) => ({
    headerTitle: 'List实现多选',
    headerTitleStyle: {
      color: 'white'
    },
    headerStyle: {
      backgroundColor: Color.kMainColor // 设置导航栏的背景颜色,headerTintColor设置无效
    },
    headerRight:(
        <NavigationItem
            title='完成'
            // 这里注意: static里面不能使用this调用方法,出现clickFinishButton is not function
            // 参考博客: http://www.jianshu.com/p/2f575cc35780
            // onPress={()=>navigation.state.params.navigatePress()}
            onPress = {()=>this.clickFinishButton()}
        />
    )
  });

解决方法:

export default class extends Component {
  static navigationOptions = ({
    navigation,
    screenProps
  }) => ({
    headerTitle: 'List实现多选',
    headerTitleStyle: {
      color: 'white'
    },
    headerStyle: {
      backgroundColor: Color.kMainColor // 设置导航栏的背景颜色,headerTintColor设置无效
    },
    headerRight:(
        <NavigationItem
            title='完成'
            // 这里注意: static里面不能使用this调用方法,出现clickFinishButton is not function
            // 参考博客: http://www.jianshu.com/p/2f575cc35780
            onPress={()=>navigation.state.params.navigatePress()}
            // onPress = {()=>this.clickFinishButton()}
        />
    )
  });
componentDidMount(){
    // 处理数据源
    this.handlerDataSource();
    this.props.navigation.setParams({navigatePress:this.clickFinishButton})
  }
  // 点击完成按钮
  clickFinishButton = ()=> {
      alert('哈哈');
    //   let data = this.state.dataArr;
    //   let selectResultArr = [];
    //   for (var index in data) {
    //         var element = object[index];
    //         if (element.isSelected) {
    //             selectResultArr.push(element);
    //         }
    //   }
    //   alert(selectResultArr.length);
  }

 

转载于:https://www.cnblogs.com/pengsi/p/7088401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值