
上QQ阅读APP看书,第一时间看更新
How to do it...
- We're going to create a new folder called images in the root of the project and add the heart image to the new folder.
- Let's import the dependencies for this class next:
import React, { Component } from 'react'; import { StyleSheet, View, Image, Text, TouchableHighlight, } from 'react-native'; const heartIcon = require('./images/heart.png');
- For this recipe, we need to keep track of whether the button has been pressed. We'll use a state object with a liked Boolean property for this purpose. The initial class should look like this:
export default class App extends React.Component { state = { liked: false, }; handleButtonPress = () => { // Defined in a later step } render() { // Defined in a later step } }
- We need to define the content of our new component inside the render method. Here, we're going to define the Image button and a Text element underneath it:
export default class App extends React.Component { state = { liked: false, }; handleButtonPress = () => { // Defined in a later step } render() { return ( <View style={styles.container}> <TouchableHighlight style={styles.button} underlayColor="#fefefe" > <Image source={heartIcon} style={styles.icon} /> </TouchableHighlight> <Text style={styles.text}>Do you like this app?</Text> </View> ); } }
- Let's define some styles to set dimensions, position, margins, colors, and so on:
const styles = StyleSheet.create({ container: { marginTop: 50, alignItems: 'center', }, button: { borderRadius: 5, padding: 10, }, icon: { width: 180, height: 180, tintColor: '#f1f1f1', }, liked: { tintColor: '#e74c3c', }, text: { marginTop: 20, }, });
- When we run the project on the simulators, we should have something similar to the following screenshot:

- In order to respond to the tap event, we need to define the content of the handleButtonPress function and assign it as a callback to the onPress property:
handleButtonPress = () => { this.setState({ liked: !this.state.liked, }); } render() { return ( <View style={styles.container}> <TouchableHighlight onPress={this.handleButtonPress} style={styles.button} underlayColor="#fefefe" > <Image source={heartIcon} style={styles.icon} /> </TouchableHighlight> <Text style={styles.text}>Do you like this app?</Text> </View> ); }
- If we test our code, we won't see anything changing on the UI, even though the state on the component changes when we press the button. Let's add a different color to the image when the state changes. That way, we'll be able to see a response from the UI:
render() { const likedStyles = this.state.liked ? styles.liked : undefined; return ( <View style={styles.container}> <TouchableHighlight onPress={this.handleButtonPress} style={styles.button} underlayColor="#fefefe" > <Image source={heartIcon} style={[styles.icon, likedStyles]} /> </TouchableHighlight> <Text style={styles.text}>Do you like this app?</Text> </View> ); }