|
import React, { Component } from "react"; |
|
import { compose } from "redux"; |
|
import hoistNonReactStatic from "hoist-non-react-statics"; |
|
/* eslint-disable no-restricted-imports */ |
|
import { withNavigationFocus } from "react-navigation"; |
|
import PropTypes from "prop-types"; |
|
|
|
// withTrackOnNavigationFocus fixes an issue with neseted stack navigators. we use this instead of |
|
// directly calling withNavigationFocus so that nested stack navigators have correct isFocused prop. |
|
function withNestedStackNavigationFocus(WrappedComponent) { |
|
class ComponentWithNestedNavigationFocus extends Component { |
|
static navigationOptions = WrappedComponent.navigationOptions; |
|
|
|
constructor(props) { |
|
super(props); |
|
this.state = { |
|
isFocused: false, |
|
}; |
|
} |
|
|
|
componentDidMount() { |
|
this.focusListener = this.props.navigation.addListener("didFocus", () => { |
|
this.setState({ isFocused: true }); |
|
}); |
|
|
|
this.blurListener = this.props.navigation.addListener("didBlur", () => { |
|
this.setState({ isFocused: false }); |
|
}); |
|
} |
|
|
|
componentWillUnmount() { |
|
this.focusListener.remove(); |
|
this.blurListener.remove(); |
|
this.setState({ isFocused: false }); |
|
} |
|
|
|
render() { |
|
return <WrappedComponent {...this.props} isFocused={this.state.isFocused} />; |
|
} |
|
} |
|
|
|
ComponentWithNestedNavigationFocus.propTypes = { |
|
navigation: PropTypes.object, |
|
}; |
|
|
|
// automatically copies all non-React static methods to this HOC. HOC's do not carry over any static methods of |
|
// original component. in the context of nav components, this messes with static `navigationOptions` . |
|
// (https://reactjs.org/docs/higher-order-components.html#static-methods-must-be-copied-over) |
|
hoistNonReactStatic(ComponentWithNestedNavigationFocus, WrappedComponent); |
|
return ComponentWithNestedNavigationFocus; |
|
} |
|
|
|
export default compose(withNavigationFocus, withNestedStackNavigationFocus); |