React-Native 样式、布局

本文介绍了React Native中的样式设置方法,包括使用style属性定义基本样式、利用StyleSheet.create集中管理样式、应用Flexbox布局规则等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

所有的核心组件都接受名为style的属性,这些样式名基本上是遵循web上的css的命名,只是按照js的语法要求使用驼峰命名法,例如将background-clor改为backgroundColor。

在实际开发中组件的样式会越来越复杂,我们建议使用StyleSheet.create来集中定义组件的样式。

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

export default class LotsOfStyles extends Component {
  render() {
    return (
      <View>
        <Text style={styles.red}>just red</Text>
        <Text style={styles.bigblue}>just bigblue</Text>
        <Text style={[styles.bigblue, styles.red]}>bigblue, then red</Text>
        <Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  bigblue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
  red: {
    color: 'red',
  },
});

flexbox

我们在React Native中使用flexbox规则来指定某个组件的子元素的布局,flexbox可以在不同屏幕尺寸上提供一致的布局结构。

一般来说,使用flexDirection alignItems和justifyContent三个样式属性就已经满足大多数局需求。

1.flex direction

在组件的style中指定的flexDirection可以决定布局的主轴,子元素是应该沿着水平轴(row)方向排列,还是沿着竖直轴(column)方向排列呢?默认值是坚直轴(column)方向。

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

export default class FlexDirectionBasics extends Component {
  render() {
    return (
      // 尝试把`flexDirection`改为`column`看看
      <View style={{flex: 1, flexDirection: 'row'}}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

2.justify content

在组件的style中指定justiryContent可以决定其子元素沿着主轴的排列方式,子元素是应该靠近主轴的起端还是末端分布。对应的这些可选项有flex-start, flex-end , center, space-around, space-between, space-evenly.

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

export default class JustifyContentBasics extends Component {
  render() {
    return (
      // 尝试把`justifyContent`改为`center`看看
      // 尝试把`flexDirection`改为`row`看看
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-between',
      }}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

3.align items

可以决定子元素沿着次轴的排列方式,子元素是应该靠近次轴的起始端还是末端。可选项:flex-start, center, flex-end , stretch.

 

最后欢迎大家访问我的个人网站:1024s​​​​​​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值