React Native 小例項 採用View佈局如下檢視

你可以叫我men發表於2016-10-09

React Native 小例項 採用View佈局如下檢視


例項步驟

1.載入View元件

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
import中新增View元件

2.建立元件

class FirstRN extends Component { //繼承方式
  render() { //渲染
    return (
      <View style={styles.container}>
      </View>
    );
  }
}

3.新增樣式表

const styles = StyleSheet.create({
  container: {
    flex: 1,
    borderWidth:1,
    borderColor:'red',
    flexDirection:'row',
    //backgroundColor: '#0f0',
  },
  item: {
    flex: 1,
    height:80,
    borderWidth:1,
    borderColor:'blue',
  },
});

4.註冊入口

AppRegistry.registerComponent('FirstRN', () => FirstRN);

5.外層佈局

<View style={styles.container}>
</View>

6. flex box水平三欄佈局

  • 外聯樣式: style={styles.container}
  • 內聯樣式: style={{flex:1,borderWidth:1}}
  • 多個樣式: style={[styles.container,{flex:1,borderWidth:1}]}

7.完善效果及整體程式碼

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

class FirstRN extends Component {
  render() {
    return (
      <View style={styles.flex}>
       <View style={styles.container}>
          <View style={[styles.item,styles.center]}>
            <Text style={styles.font}>酒店</Text>
          </View>
          <View style={[styles.item, styles.lineLeftRight]}>
            <View style={[styles.flex, styles.center, styles.lineCenter]}>
              <Text style={styles.font}>海外酒店</Text>
            </View>
            <View style={[styles.flex, styles.center]}>
              <Text style={styles.font}>特惠酒店</Text>
            </View>
          </View>
          <View style={[styles.item, styles.lineLeftRight]}>
             <View style={[styles.flex, styles.center,styles.lineCenter]}>
              <Text style={styles.font}>團購</Text>
            </View> 
            <View style={[styles.flex, styles.center]}>
              <Text style={styles.font}>客棧,公寓</Text>
            </View>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    marginTop: 200,
    marginLeft: 5,
    marginRight: 5,
    height: 85,
    flexDirection: 'row',
    borderRadius: 5,
    padding: 2,
    backgroundColor: '#FF0067',
  },
  item: {
    flex: 1,
    height: 80,
  },
  center: {
    justifyContent: 'center',
    alignItems: 'center'
  },
  flex: {
    flex: 1,
  },
  font: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  lineLeftRight: {
    borderLeftWidth: 1/PixelRatio.get(),
    borderRightWidth: 1/PixelRatio.get(),//自帶函式
    borderColor: '#fff',
  },
  lineCenter: {
    borderBottomWidth: 1/PixelRatio.get(),
    borderColor: '#fff',
  },
});

AppRegistry.registerComponent('FirstRN', () => FirstRN);
  • 最終結果如下

相關文章