เมื่อติดตั้ง ReactNative บนระบบของคุณแล้ว คุณควรได้รับรหัสเริ่มต้นใน App.js ดังนี้ -
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style = {styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
}); ตอนนี้คุณสามารถเปลี่ยนรหัสได้ตามความต้องการของคุณ เราสนใจที่นี่เพื่อแสดงข้อความ Hello World ในแอป
ในการเริ่มต้น คุณต้องนำเข้าส่วนประกอบและโมดูลที่จำเป็นก่อน เราต้องการโมดูล React ดังนั้นมานำเข้ากันก่อนดังที่แสดงด้านล่าง -
import React from 'react';
ต่อไป มานำเข้าส่วนประกอบอื่นๆ ที่เราจะใช้ในโค้ดของเราเพื่อแสดงข้อความ Hello World
import { StyleSheet, Text, View } from 'react-native'; เราได้นำเข้าองค์ประกอบ StyleSheet ข้อความและมุมมอง เราต้องการองค์ประกอบ StyleSheet เพื่อจัดรูปแบบองค์ประกอบมุมมองและข้อความ องค์ประกอบ View จะเป็นองค์ประกอบหลักที่จะมีองค์ประกอบ Text เป็นลูกของมัน
แอปเป็นคลาสเริ่มต้นที่ส่งออกและคุณเรียกใช้โครงการ คุณควรจะเห็นข้อความในองค์ประกอบ
export default class App extends React.Component {
render() {
return (
<View style = {styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
</View>
);
}
} เปลี่ยนข้อความเป็น Hello World ดังที่แสดงด้านล่าง -
export default class App extends React.Component {
render() {
return (
<View style = {styles.container}>
<Text>Hello World</Text>
</View>
);
}
} อุปกรณ์ประกอบฉากของสไตล์ถูกเพิ่มไปยังองค์ประกอบมุมมอง ค่าที่กำหนดคือ styles.container ต้องระบุค่าอุปกรณ์ประกอบฉากในวงเล็บปีกกา {} เช่น style={styles.container}.
วัตถุสไตล์ถูกสร้างขึ้นโดยใช้ StyleSheet.create() คุณสามารถกำหนดสไตล์ทั้งหมดของคุณสำหรับส่วนประกอบภายใน StyleSheet.create() ตอนนี้เราได้กำหนดรูปแบบคอนเทนเนอร์ที่ใช้ในองค์ประกอบมุมมองเป็น
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
forText: {
color: 'green',
fontSize: '25px'
}
}); นี่คือรหัสเต็มที่ช่วยแสดง Hello World บนหน้าจอมือถือของคุณโดยใช้ ReactNative
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style = {styles.container}><Text style={styles.forText}>Hello World</Text></View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
forText: {
color: 'green',
fontSize: '25px'
}
}); ผลลัพธ์
