Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เขียนโปรแกรมแสดง Hello World ใน React Native


หลังจากติดตั้ง React Native แล้ว คุณจะได้โค้ดเริ่มต้นใน App.js ดังนี้:

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

export default class App extends React.Component {
  render() {
    return (
      
        Open up App.js to start working on your app!
        Changes you make will automatically reload.
        Shake your phone to open the developer menu.
      
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

ตอนนี้คุณสามารถแก้ไขโค้ดตามต้องการ เราจะเปลี่ยนให้แสดงข้อความ "Hello World"

ขั้นตอนการสร้าง Hello World

1. นำเข้าโมดูลที่จำเป็น

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

เราต้องการ StyleSheet สำหรับจัดสไตล์ Text สำหรับแสดงข้อความ และ View เป็นคอมโพเนนต์ผู้ปกครอง (parent)

2. แก้ไขคอมโพเนนต์ App

export default class App extends React.Component {
  render() {
    return (
      
        Hello World
      
    );
  }
}

3. กำหนดสไตล์

Props style ส่งค่าเป็นอ็อบเจ็กต์ในวงเล็บปีกกา style={styles.container}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  forText: {
    color: 'green',
    fontSize: '25px'
  }
});

4. โค้ดเต็มรูปแบบ

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

export default class App extends React.Component {
  render() {
    return (
      
        Hello World
      
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  forText: {
    color: 'green',
    fontSize: '25px'
  }
});

ผลลัพธ์

เขียนโปรแกรมแสดง Hello World ใน React Native

หมายเหตุ

  • ใน React Native สิ้นสุด จะแนะนำให้ใช้ Functional Component พร้อม Hooks แทน Class Component
  • ตัวอย่างสมัยใหม่จะใช้ const App = () => { ... } แทน