React-Navigation 中withNavigation、withNavigationFocus高阶组件的使用

在这里插入图片描述

在2.18版本中的React-Navigation中有两个很实用的高阶组件,在这里我们进行说明一下:

一、withNavigation

withNavigation是一个高阶组件,它可以将 navigation 这个 prop 传递到一个包装的组件。 当你无法直接将 navigation 这个 prop 传递给当前组件的时候,或者不想在深度嵌套的子组件中传递它时,它将非常有用,能够直接使用这个高阶组件进行包装需要navigation属性的组件即可

1. API接口
withNavigation (Component) -返回一个 Component。

如下面使用方式,我们通过直接使用withNavigation使得组件MyBackButton中直接含有navigation属性,能够进行调用goBack()方法:

import React from 'react';
import { Button } 'react-native';
import { withNavigation } from 'react-navigation';

class MyBackButton extends React.Component {
  render() {
    return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
  }
}

// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);
二、withNavigationFocus

withNavigationFocus是一个高阶组件,它可以将 isFocused `这个 prop 传递到一个包装的组件。 如果你需要在页面组件的 render 方法中使用焦点状态,或者在页面内某个位置渲染另一个组件时,这个组件很有用。

1. API如下
withNavigationFocus (Component) - 返回一个 Component。

使用方法如下所示,我们通过使用withNavigationFocus组件进行包装组件FocusStateLabel,从而获取到isFocused状态进行判断,值得说明的是,这个效果是和从navigation属性中方法isFocus()方法值是一致的

import React from 'react';
import { Text } 'react-native';
import { withNavigationFocus } from 'react-navigation';

class FocusStateLabel extends React.Component {
  render() {
    return <Text>{this.props.isFocused ? 'Focused' : 'Not focused'}</Text>;
  }
}

// withNavigationFocus returns a component that wraps FocusStateLabel and passes
// in the navigation prop
export default withNavigationFocus(FocusStateLabel);

在这里插入图片描述

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐