編寫一個程式,在 React Native 中顯示“Hello World”?
React Native 安裝到您的系統後,您應該在 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、Text 和 View 元件。我們需要 StyleSheet 元件來設定 View 和 Text 元件的樣式。View 元件將是父元件,Text 元件將是其子元件。
App 是匯出的預設類,執行專案後,您應該能夠在裝置上看到 `
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>
);
}
}樣式的 props 新增到 View 元件。給定的值是 styles.container。props 值必須放在花括號 {} 中,即 style={styles.container}。
styles 物件是使用 StyleSheet.create() 建立的。您所有元件的樣式都可以在 StyleSheet.create() 內定義。現在我們已經定義了用於 View 元件的容器樣式 `
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
forText: {
color: 'green',
fontSize: '25px'
}
});這是使用 React Native 在您的移動螢幕上顯示 Hello World 的完整程式碼。
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'
}
});輸出

廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP