Skip to content

Instantly share code, notes, and snippets.

@florentroques
Last active September 23, 2017 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florentroques/12799b7fead0c0d0a7e2b20b07e2b723 to your computer and use it in GitHub Desktop.
Save florentroques/12799b7fead0c0d0a7e2b20b07e2b723 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { Text, FlatList, View, StyleSheet, Button } from 'react-native';
import { Constants } from 'expo';
const TouchableTextConst = props => {
console.log(`TouchableTextConst${props.id} rendered, callback (re)created :(`);
const textPressed = () => {
props.onPressItem(props.id);
};
return (
<Text style={styles.item} onPress={textPressed}>{props.children}</Text>
);
};
class TouchableTextClass extends React.PureComponent {
constructor(props) {
super(props);
this.textPressed = this.textPressed.bind(this);
}
textPressed(){
this.props.onPressItem(this.props.id);
}
render() {
console.log(`TouchableTextClass${this.props.id} rendered, element only :)`);
return (
<Text style={styles.item} onPress={this.textPressed}>
{this.props.children}
</Text>
);
}
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
clicks: 0,
};
//event binding in constructor for performance (happens only once)
//see facebook advice:
//https://facebook.github.io/react/docs/handling-events.html
this.handlePress = this.handlePress.bind(this);
this.increment = this.increment.bind(this);
}
increment() {
const { clicks } = this.state;
this.setState({
clicks: clicks + 1,
});
}
handlePress(id) {
//Do what you want with the id
console.log(`${id} pressed`);
}
render() {
return (
<View style={styles.container}>
<Button onPress={this.increment} title={'Tap to re render'} />
<Text>{this.state.clicks}</Text>
<View style={styles.listsContainer}>
<View>
<Text>WithClassFLatList</Text>
<FlatList
data={[
{ id: 'WithClass1' },
{ id: 'WithClass2' },
{ id: 'WithClass3' },
{ id: 'WithClass4' },
{ id: 'WithClass5' },
]}
renderItem={({ item }) => (
<TouchableTextClass id={item.id} onPressItem={this.handlePress}>
{item.id}
</TouchableTextClass>
)}
/>
</View>
<View>
<Text>WithConstFLatList</Text>
<FlatList
data={[
{ id: 'WithConst1' },
{ id: 'WithConst2' },
{ id: 'WithConst3' },
{ id: 'WithConst4' },
{ id: 'WithConst5' },
]}
renderItem={({ item }) => (
<TouchableTextConst id={item.id} onPressItem={this.handlePress}>
{item.id}
</TouchableTextConst>
)}
/>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
listsContainer: {
marginTop: 25,
flex: 1,
flexDirection: 'row',
},
item: {
margin: 5,
padding: 15,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
color: '#34495e',
backgroundColor: 'yellow',
},
});