1 min read

React Native Framework en quelques exemples

When Facebook goes FOSS and creates a mobile app framework : here comes react-native !

'Hello World!'

import React from 'react';  // Obligatoire pour chaque app.js pour utilise Bibliothèque React
import {Text, View} from 'react-native';

const HelloWorldApp = () => {
  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      }}> 
      <Text>Hello, world!</Text>
      <Text>Heyhey</Text>
    </View>
  ); // Retour un contenant (View) et les contenus (Text) 
};
export default HelloWorldApp; 

Props et State

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

// React Native Styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

const Greeting = props => {
  return (
    <View style={styles.container}>
      <Text>Hello {props.name}!</Text>
    </View>
  );
};

const LotsOfGreetings = () => {
  const [count, setCount] = useState(0);    
  return (
    <View style={styles.container}>
      <Greeting name="Rexxar" />
      <Greeting name="Jaina" />
      <Greeting name="Valeera" />
      <Text>You clicked {count} times</Text>
      <Button
        onPress={() => setCount(count + 1)}
        title="Click me!"
      />
    </View>
    
  );
};

export default LotsOfGreetings;

Il s'agit d'une structure imbriquée. Le rendu du contenu est assuré par LotsOFGreetings(), tandis que Greeting() spécifie le modèle et styles() spécifie le style.

Class

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

class App extends Component {
  state = {
    count: 0,
  };

  countAddOne = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity style={styles.button} onPress={this.countAddOne}>
          <Text>Click me</Text>
        </TouchableOpacity>
        <View>
          <Text>You clicked {this.state.count} times</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 10,
    marginBottom: 10,
  },
});

export default App;