Created
January 13, 2017 16:29
-
-
Save Lepozepo/79594a7974dd8bc785cffd8b36b0285d to your computer and use it in GitHub Desktop.
React without Context Coupling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from 'react'; | |
import { ScrollView, TextInput } from 'react-native'; | |
// Parent Component | |
class Card extends Component { | |
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 { | |
handleFocus = () => { | |
if (!this.props.onFocus) return; | |
this.props.onFocus(this.yPosition); | |
} | |
handleLayout = ({nativeEvent:{layout:{ y }}}) => { | |
this.yPosition = y; | |
} | |
render() { | |
return ( | |
<TextInput | |
onLayout={this.handleLayout} | |
onFocus={this.handleFocus} | |
/> | |
); | |
} | |
} | |
// A developer using your weak non-contextual component | |
class Cards extends Component { | |
render() { | |
return ( | |
<Card ref={(r) => {this.card = r;}}> | |
<CardTextInput | |
onFocus={this.card && this.card.handleFocus} | |
/> | |
</Card> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment