Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

React Native 填坑之旅:Flexbox 佈局入門

編輯:關於 Android 程式設計

程式碼:https://github.com/future-challenger/petshop/tree/master/client/petshop/src/controller

回頭看這個系列,一路寫下來其實都是我在開發中踩過的坑與解法,興之所至、不問順序。因此系列內容和知識本身的學習順序並不一致,比如今天要談的佈局——這其實是動手寫 App 之前就該弄懂的基礎,否則看到 <View> 第一反應會是「這是什麼?」

等系列推進到一定程度,我會重新整理成依知識順序排列的版本,讓讀者能循序學習,不必在開發中遇到本可避免的問題。

暖身:NavigationBar 的按鈕為什麼貼齊上緣?

預設情況下,NavigationBar 左側的返回鍵看起來會頂到上沿。當時的寫法大概是這樣:

<TouchableHighlight
    onPress={() => { if (index > 0) navigator.pop(); }}>
    <Text style={{ marginLeft: 10 }}>Back</Text>
</TouchableHighlight>

想讓它垂直居中,直接在 TouchableHighlight 上加樣式是沒有效果的。正確做法是在外層多包一個 View,並把樣式設在外層:

<View style={{ justifyContent: 'center' }}>
    <TouchableHighlight
        onPress={() => { if (index > 0) navigator.pop(); }}>
        <Text style={{ marginLeft: 10 }}>Back</Text>
    </TouchableHighlight>
</View>

這是 React Native 佈局很典型的一課:樣式要加在容器上,不是加在葉節點上。

主題:三個 View 疊在一起,如何只顯示一個?

情境是這樣的:我們有三個等寬、橫向排列的 View,對應三個按鈕,點哪個按鈕就顯示對應的 View,同一時間只顯示一個。

Flex 的方向

先看會出問題的寫法:

<View style={{ marginTop: 30 }}>
    <View style={{ backgroundColor: 'red', height: 100 }} />
    <View style={{ backgroundColor: 'orange', height: 100 }} />
    <View style={{ backgroundColor: 'yellow', height: 100 }} />
</View>

結果是紅、橙、黃三塊垂直堆疊。原因是 React Native 採用 Flexbox,而:

column 是預設的 flex 方向,由上到下。
row 則是由左到右。

改成 row 之後:

<View style={{ flexDirection: 'row', marginTop: 30 }}>
    <View style={{ backgroundColor: 'red', flex: 1, height: 100 }} />
    <View style={{ backgroundColor: 'orange', flex: 1, height: 100 }} />
    <View style={{ backgroundColor: 'yellow', flex: 1, height: 100 }} />
</View>

三塊就並排且等寬了。

JustifyContent 與 AlignItems

當 flexDirection 決定了排列方向,還需要微調對齊方式時,就用這兩個屬性:

justifyContent 作用在主軸(等同 flexDirection 指定的方向);alignItems 作用在交叉軸。若 flexDirection 是 column,主軸就是垂直方向,交叉軸則是水平方向。

Flex 的值

flex 為相同正數:兄弟節點按比例瓜分父容器空間。

flex 為 0:完全聽從自己的 width/height,系統不會幫你計算,沒設尺寸就是 0。

flex 為 -1:尺寸由 width/height 決定,但空間不足時會被壓縮,且不會小於 minWidth/minHeight。

實作:用 state 切換顯示

export default class FlexDemo extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            view1Style: { flex: 1, width: 0 },   // flex 不為 0 時 width 不生效
            view2Style: { flex: 0, width: 0 },
            view3Style: { flex: 0, width: 0 }
        };
        this._onPress = this._onPress.bind(this);
    }

    _onPress(buttonIndex) {
        const styles = [
            { flex: 1, width: 0 },
            { flex: 0, width: 0 },
            { flex: 0, width: 0 }
        ];
        styles[buttonIndex] = { flex: 1, width: 0 };
        this.setState({
            view1Style: styles[0],
            view2Style: styles[1],
            view3Style: styles[2]
        });
    }

    render() {
        return (
            <View style={{ flexDirection: 'row', marginTop: 30 }}>
                <View style={[{ backgroundColor: 'red', height: 100 }, this.state.view1Style]} />
                <View style={[{ backgroundColor: 'orange', height: 100 }, this.state.view2Style]} />
                <View style={[{ backgroundColor: 'yellow', height: 100 }, this.state.view3Style]} />

                <View style={{
                    position: 'absolute', bottom: 0, left: 0, right: 0,
                    height: 60, flexDirection: 'row',
                    justifyContent: 'center', alignItems: 'center',
                    backgroundColor: '#000', opacity: 0.6
                }}>
                    {[0, 1, 2].map(i => (
                        <TouchableOpacity key={i} onPress={() => this._onPress(i)}>
                            <Text style={{ color: '#fff', padding: 10 }}>{i + 1}</Text>
                        </TouchableOpacity>
                    ))}
                </View>
            </View>
        );
    }
}

原理:要改變一個元件的佈局,核心就是 setState。一開始把三個子 View 的樣式都放進 state,按鈕的點擊事件只負責改 state,畫面自然跟著變。

關鍵技巧在於前面提過的規則:flex 不為 0 時 width 不會生效。所以初始狀態讓紅色 View 的 flex 為 1、其餘為 0 且寬度為 0,切換時把目標 View 的 flex 設為 1、其他設為 0,就能做到「同一時間只顯示一個」。

留個練習

上面這個效果,對這麼簡單的三個 View 來說,其實也可以用條件渲染(conditional render)實作。請你動手改寫成那個版本,對比兩種做法在效能與可讀性上的差異。

結語

以上都是我實際遇到的問題,涵蓋了 Flexbox 的幾個核心概念。React Native 的佈局體系內容還很多,後續會在系列文章中繼續補充。建議一邊動手做小 demo,一邊對照官方文件的 Flexbox 章節,這塊的學習曲線只有在實作中才會真正下降。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved