Skip to content

Instantly share code, notes, and snippets.

@Lepozepo
Last active January 13, 2017 16:52
Show Gist options
  • Save Lepozepo/e6c3a544f5c35bf296df1b27de875746 to your computer and use it in GitHub Desktop.
Save Lepozepo/e6c3a544f5c35bf296df1b27de875746 to your computer and use it in GitHub Desktop.
import { Component, PropTypes } from 'react';
import { ScrollView, TextInput } from 'react-native';
// Parent Component
class Card extends Component {
static childContextTypes = {
handleFocus: PropTypes.func,
}
getChildContext = () => ({
handleFocus: this.handleFocus,
})
handleFocus = (y) => {
this.scrollView.scrollTo({ y });
}
render() {
const {children} = this.props;
return (
<ScrollView ref={(r) => {this.scrollView = r}}>
{children}
</ScrollView>
);
}
}
// Child Component
class CardTextInput extends Component {
static contextTypes = {
handleFocus: PropTypes.func,
}
handleFocus = () => {
if (!this.context.handleFocus) return;
this.context.handleFocus(this.yPosition);
}
handleLayout = ({nativeEvent:{layout:{ y }}}) => {
this.yPosition = y;
}
render() {
return (
<TextInput
onLayout={this.handleLayout}
onFocus={this.handleFocus}
/>
);
}
}
// A developer using your awesome it-just-works component
class Cards extends Component {
render() {
return (
<Card>
<CardTextInput />
</Card>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment