React Native - 樣式



有幾種方法可以在 React Native 中對元素進行樣式設定。

可以使用 style 屬性內聯新增樣式。但是,這不屬於最佳實踐,因為它可能會導致程式碼難以閱讀。

在本章中,我們將使用 樣式表 來進行樣式設定。

容器元件

在本節中,我們將簡化我們前一章中的容器元件。

App.js

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

export default class App extends React.Component {
   state = {
      myState: 'This is my state'
   }
   render() {
      return (
         <View>
            <PresentationalComponent myState = {this.state.myState}/>
         </View>
      );
   }
}

表示性元件

在以下示例中,我們將匯入 StyleSheet。在檔案的底部,我們將建立我們的樣式表,並將其分配給 styles 常量。請注意,我們的樣式採用 駝峰式,且在樣式設定中不使用 px 或 %。

要將樣式應用到我們的文字中,我們需要向 Text 元素新增 style = {styles.myText} 屬性。

PresentationalComponent.js

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

const PresentationalComponent = (props) => {
   return (
      <View>
         <Text style = {styles.myState}>
            {props.myState}
         </Text>
      </View>
   )
}
export default PresentationalComponent

const styles = StyleSheet.create ({
   myState: {
      marginTop: 20,
      textAlign: 'center',
      color: 'blue',
      fontWeight: 'bold',
      fontSize: 20
   }
})

當我們執行應用程式時,將收到以下輸出。

React Native Styling
廣告