您的位置:首页 > Web前端 > React

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

2018-10-20 21:04 1501 查看
版权声明:本文为博主原创文章,若需转载,请注明出处 https://blog.csdn.net/suwu150/article/details/83216893

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: