UNPKG

react-navigation

Version:
54 lines (45 loc) 1.48 kB
import React from 'react'; import propTypes from 'prop-types'; import hoistStatics from 'hoist-non-react-statics'; import invariant from '../utils/invariant'; import withNavigation from './withNavigation'; export default function withNavigationFocus(Component) { class ComponentWithNavigationFocus extends React.Component { static displayName = `withNavigationFocus(${Component.displayName || Component.name})`; constructor(props) { super(props); this.state = { isFocused: props.navigation ? props.navigation.isFocused() : false, }; } componentDidMount() { const { navigation } = this.props; invariant( !!navigation, 'withNavigationFocus can only be used on a view hierarchy of a navigator. The wrapped component is unable to get access to navigation from props or context.' ); this.subscriptions = [ navigation.addListener('didFocus', () => this.setState({ isFocused: true }) ), navigation.addListener('willBlur', () => this.setState({ isFocused: false }) ), ]; } componentWillUnmount() { this.subscriptions.forEach(sub => sub.remove()); } render() { return ( <Component {...this.props} isFocused={this.state.isFocused} ref={this.props.onRef} /> ); } } return hoistStatics(withNavigation(ComponentWithNavigationFocus), Component); }