Cours React Native · Module 2: Listes et styles

Code spécifique à la plateforme

3 min de lecture ·
Dans cette leçon3

React Native te permet d'écrire du code spécifique à iOS ou Android.

Platform.OS

import { View, Text, StyleSheet, Platform } from 'react-native';

export default function PlatformExample() {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        Plateforme : {Platform.OS}
      </Text>
      <Text style={styles.text}>
        Version : {Platform.Version}
      </Text>

      {/* Rendu conditionnel */}
      {Platform.OS === 'ios' && (
        <Text style={styles.iosOnly}>iOS uniquement !</Text>
      )}

      {Platform.OS === 'android' && (
        <Text style={styles.androidOnly}>Android uniquement !</Text>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1a5276',
  },
  text: {
    fontSize: 18,
    color: '#fff',
    marginBottom: 10,
  },
  iosOnly: {
    fontSize: 16,
    color: '#3498db',
    marginTop: 20,
  },
  androidOnly: {
    fontSize: 16,
    color: '#2ecc71',
    marginTop: 20,
  },
});

Platform.select()

import { View, Text, StyleSheet, Platform } from 'react-native';

export default function PlatformSelectExample() {
  const instructions = Platform.select({
    ios: 'Appuie sur Cmd+D pour ouvrir le menu développeur',
    android: 'Secoue le téléphone pour ouvrir le menu développeur',
    default: 'Plateforme non reconnue',
  });

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Instructions :</Text>
      <Text style={styles.instructions}>{instructions}</Text>

      {/* Composants spécifiques à la plateforme */}
      <View style={styles.button}>
        <Text style={styles.buttonText}>Bouton</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#1a5276',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 10,
  },
  instructions: {
    fontSize: 14,
    color: '#bdc3c7',
    textAlign: 'center',
    marginBottom: 30,
  },
  button: {
    paddingVertical: 14,
    paddingHorizontal: 28,
    borderRadius: Platform.select({
      ios: 12,
      android: 4,
    }),
    backgroundColor: Platform.select({
      ios: '#007AFF', // Bleu iOS
      android: '#6200EE', // Violet Material
    }),
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.25,
        shadowRadius: 4,
      },
      android: {
        elevation: 4,
      },
    }),
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});

Fichiers spécifiques à la plateforme

Tu peux créer des fichiers séparés pour chaque plateforme :

components/
├── Button.tsx          # Utilisé quand il n'y a pas de fichiers spécifiques
├── Button.ios.tsx      # Utilisé uniquement sur iOS
└── Button.android.tsx  # Utilisé uniquement sur Android
// Button.ios.tsx
import { Pressable, Text, StyleSheet } from 'react-native';

export default function Button({ title, onPress }) {
  return (
    <Pressable style={styles.button} onPress={onPress}>
      <Text style={styles.text}>{title}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#007AFF',
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 10,
  },
  text: {
    color: '#fff',
    fontSize: 17,
    fontWeight: '600',
  },
});
// Button.android.tsx
import { Pressable, Text, StyleSheet } from 'react-native';

export default function Button({ title, onPress }) {
  return (
    <Pressable
      style={styles.button}
      onPress={onPress}
      android_ripple={{ color: 'rgba(255,255,255,0.3)' }}
    >
      <Text style={styles.text}>{title}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#6200EE',
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 4,
    elevation: 2,
  },
  text: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '500',
    textTransform: 'uppercase',
    letterSpacing: 1,
  },
});

L'import sélectionnera automatiquement le bon fichier :

import Button from './components/Button';
// Sur iOS, cela chargera Button.ios.tsx
// Sur Android, cela chargera Button.android.tsx
Code de cette leçon : App.tsx
import React from 'react';
import { View, Text, StyleSheet, Platform } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Porte de l'Atlantide</Text>
      <View style={styles.button}>
        <Text style={styles.buttonText}>Ouvrir la porte</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1a5276',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 20,
  },
  button: {
    paddingVertical: 14,
    paddingHorizontal: 28,
    // TODO : utilise Platform.select pour définir borderRadius à 12 sur iOS et 4 sur android.
    //   Syntaxe : borderRadius: Platform.select({ ios: 12, android: 4 }),
    // TODO : utilise Platform.select pour définir backgroundColor à '#007AFF' sur iOS
    //   et '#6200EE' sur android.
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Quelles valeurs Platform.OS peut-il renvoyer ?

  2. 2. Comment React Native traite-t-il les fichiers avec les extensions .ios.tsx et .android.tsx ?

Tâches pratiques dans le jeu

  • Clique dans l'ordre

    Clique sur les éléments de Platform.select dans le bon ordre :

  • Éditeur de code

    Complète le code en utilisant Platform.select.

Articles utiles