Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Touchable Components | Styling and Navigation
React Native Fundamentals

Touchable Components

Sveip for å vise menyen

React Native provides several built-in components for handling touch interactions. One of the most commonly used is TouchableOpacity, which allows users to interact with elements such as buttons, cards, and icons.

When a user presses a TouchableOpacity component, its opacity decreases slightly, creating visual feedback that indicates the touch was registered. This makes it a simple and effective way to build interactive mobile interfaces.

TouchableOpacity accepts an onPress prop, which is a function that runs when the user taps the component. You can place any React Native elements inside it, including Text, View, or Image components.

React Native also includes other touchable components, such as TouchableHighlight, which provides feedback by displaying a highlight color behind the wrapped element when pressed. However, TouchableOpacity is often the preferred choice for simple buttons and user interactions.

The example below creates a button that changes opacity when pressed and displays an alert message.

import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Alert,
} from 'react-native';

export default function App() {
  const handlePress = () => {
    Alert.alert('Button Pressed', 'You tapped the button.');
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={styles.button}
        activeOpacity={0.6}
        onPress={handlePress}
      >
        <Text style={styles.buttonText}>Press Me</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#007AFF',
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 8,
  },
  buttonText: {
    color: '#FFFFFF',
    fontSize: 18,
  },
});

In this example, TouchableOpacity wraps a Text component and acts as a button. The activeOpacity property controls how transparent the button becomes while pressed. When the user taps the button, the onPress function runs and displays an alert message.

question mark

Which component provides feedback by changing opacity when pressed?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 4

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 4
some-alt