ReactNative學習筆記(六)之重新組織應用的樣式
我們建立的應用不可能把所有的東西都放在一個檔案裡面, 我們可以按照自己的想法去組織一下應用的程式碼.
首先我們想辦法把樣式分離出來, 放到另一個檔案當中.
在根目錄下建立一個資料夾app, 然後在app資料夾下建立一個Styles資料夾, 在Styles資料夾中建立一個叫做Main.js的js檔案

然後將App.js中styles相關的程式碼剪下進來, 然後需要注意的是用到了 StyleSheet.create
這句程式碼所以StyleSheet這個包是也是需要導進來的, 所以Main.js的完整程式碼如下
import {StyleSheet} from 'react-native'; let styles = StyleSheet.create({ redText: { color: '#db2828', fontSize: 15, }, itemMeta: { fontSize: 16, color: 'rgba(0, 0, 0, 0.6)', marginBottom: 6, }, itemHeader: { fontSize: 18, fontFamily: 'Helvetica Neue', fontWeight: '300', color: '#6435c9', marginBottom: 6, }, itemContent: { flex: 1,// 大概就是weight的意思吧, 佔剩下面積的100%, 否則flex就是stretch, 會把裡面的text元件的寬度伸展開來, // 一行中的文字太多的話會跑到外面去, 可以將這個flex: 1註釋掉看一下效果就知道了 marginLeft: 13, marginTop: 6, }, item: { flexDirection: 'row', borderBottomWidth: 1, borderColor: 'rgba(100, 53, 201, 0.1)', paddingBottom: 6, marginBottom: 6, flex: 1, // todo 這裡的flex等於1到底有什麼用 }, loading: { flex: 1,// todo 這裡的flex等於1到底有什麼用 justifyContent: 'center', alignItems: 'center', }, overlay: { backgroundColor: 'rgba(0, 0, 0, 0.1)', alignItems: 'center', }, overlayHeader: { fontSize: 33, fontFamily: 'Helvetica Neue', fontWeight: '200', color: '#eae7ff', padding: 10, }, overlaySubHeader: { fontSize: 16, fontFamily: 'Helvetica Neue', fontWeight: '200', color: '#eae7ff', padding: 10, paddingTop: 0, }, backgroundImage: { flex: 1, resizeMode: 'cover', // contain, stretch(拉伸) }, image: { width: 99, height: 138, margin: 6, }, itemOne: { alignSelf: 'stretch', // stretch: 伸展、張開 }, itemTwo: { alignSelf: 'flex-end', }, itemThree: { // alignSelf: 'flex-end', // flex: 2, }, itemText: { fontSize: 33, fontFamily: 'Helvetica Neue', fontWeight: '200', color: '#6435c9', padding: 30, }, container: { // justifyContent: 'space- around', // alignItems: 'flex-start', flexDirection: 'row', backgroundColor: '#eae7ff', flex: 1, // 佔滿全屏 paddingTop: 23, } }); export {styles as default}; // 注意這裡的styles是上面的let styles
最後記得將這個styles變數匯出, 語法就是 export { xxx as default}
, 這個xxx就是在檔案中定義的變數styles
然後我們需要在App.js檔案中匯入這個樣式
import styles from './app/Styles/Main';
app資料夾和App.js檔案在同一層級目錄, 所以用 ./app/xxx/
, 然後再一層層去引用到Main.js檔案, ./
表示當前檔案所在的目錄, 而 ../
就表示當前檔案的上級目錄
執行效果
成功的跑了起來, 樣式也是對的, 說明程式碼重構成功!