React Native鸿蒙开发实战(二):基础组件与Flex布局

React Native鸿蒙开发实战(二):基础组件与Flex布局

一、核心基础组件详解

React Native在鸿蒙平台上提供了与Web开发类似的基础组件体系,这些组件是构建界面的基本元素。

1.1 View组件 - 布局容器

View组件是React Native中最基础的容器组件,相当于HTML中的div元素。它支持Flexbox布局,可以包裹其他组件并设置样式。

复制代码
import { View, Text } from 'react-native';

const MyView = () => (
  <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
    <Text>Hello, World!</Text>
  </View>
);

关键属性

  • flex:定义组件在容器中的弹性比例
  • justifyContent:主轴对齐方式(flex-start、center、flex-end、space-between、space-around)
  • alignItems:交叉轴对齐方式
  • backgroundColor:背景颜色

1.2 Text组件 - 文本显示

Text组件用于显示文本内容,支持样式设置和嵌套。

复制代码
import { Text } from 'react-native';

const MyText = () => (
  <Text style={{ fontSize: 16, color: '#333', fontWeight: 'bold' }}>
    Welcome to React Native!
  </Text>
);

常用样式属性

  • fontSize:字体大小
  • color:字体颜色
  • fontWeight:字体粗细
  • textAlign:文本对齐方式

1.3 Image组件 - 图片显示

Image组件用于显示本地或网络图片,支持多种图片格式。

复制代码
import { Image } from 'react-native';

// 本地图片
<Image source={require('./images/icon.png')} style={{ width: 100, height: 100 }} />

// 网络图片
<Image source={{ uri: 'https://example.com/image.png' }} style={{ width: 200, height: 200 }} />

关键属性

  • source:图片资源路径
  • resizeMode:图片缩放模式(cover、contain、stretch等)
  • onLoad:图片加载完成回调

二、Flex布局在鸿蒙平台的适配

2.1 Flex布局基础

React Native使用Flexbox布局模型,与CSS Flexbox类似但存在一些差异。在鸿蒙平台上,Flex布局的默认行为与Android/iOS有所不同。

复制代码
const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row', // 主轴方向:row(水平)或column(垂直)
    justifyContent: 'space-between', // 主轴对齐
    alignItems: 'center', // 交叉轴对齐
    padding: 16,
  },
});

鸿蒙平台差异

  • 默认flexDirectioncolumn(垂直排列)
  • 百分比宽度(width: '50%')在低版本鸿蒙上可能失效
  • justifyContent: 'space-between'在某些场景下需要特殊处理

2.2 常用布局模式

水平居中布局
复制代码
<View style={{ 
  flex: 1, 
  justifyContent: 'center', 
  alignItems: 'center' 
}}>
  <Text>居中内容</Text>
</View>
等分布局
复制代码
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
  <View style={{ width: '30%', height: 50, backgroundColor: 'red' }} />
  <View style={{ width: '30%', height: 50, backgroundColor: 'green' }} />
  <View style={{ width: '30%', height: 50, backgroundColor: 'blue' }} />
</View>
响应式布局
复制代码
import { Dimensions } from 'react-native';

const { width } = Dimensions.get('window');

<View style={{ width: width * 0.8, height: 200 }}>
  {/* 内容 */}
</View>

三、样式系统与单位换算

3.1 StyleSheet样式系统

React Native使用StyleSheet.create创建样式对象,这种方式有性能优化优势。

复制代码
import { StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
    padding: 20,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 20,
  },
});

// 使用样式
<View style={styles.container}>
  <Text style={styles.title}>标题</Text>
</View>

优势

  • 提前验证样式合法性,避免运行时错误
  • 样式可复用,减少重复代码
  • 性能优化:样式对象会被缓存

3.2 像素单位换算

在鸿蒙平台上,推荐使用绝对单位(px)而非百分比,避免布局错乱问题。

复制代码
import { PixelRatio } from 'react-native';

// dp转px
const dp2px = (dp) => PixelRatio.getPixelSizeForLayoutSize(dp);

// px转dp
const px2dp = (px) => PixelRatio.roundToNearestPixel(px);

// 使用示例
<View style={{ width: dp2px(100), height: dp2px(100) }} />

鸿蒙单位系统

  • px:物理像素单位
  • vp:屏幕密度相关像素(类似Android的dp)
  • fp:字体像素(类似Android的sp)
  • lpx:视窗逻辑像素单位

适配建议

  • 使用Dimensions.get('window')获取屏幕尺寸
  • 避免使用百分比布局,改用绝对单位计算
  • 针对不同设备尺寸设置断点

四、实战案例:新闻卡片布局

复制代码
import React from 'react';
import { View, Text, Image, StyleSheet, Dimensions } from 'react-native';

const { width } = Dimensions.get('window');

const NewsCard = ({ title, summary, imageUrl, date }) => {
  return (
    <View style={styles.card}>
      <Image 
        source={{ uri: imageUrl }} 
        style={styles.image} 
        resizeMode="cover"
      />
      <View style={styles.content}>
        <Text style={styles.title} numberOfLines={2}>{title}</Text>
        <Text style={styles.summary} numberOfLines={3}>{summary}</Text>
        <Text style={styles.date}>{date}</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  card: {
    width: width - 32,
    backgroundColor: '#fff',
    borderRadius: 8,
    marginBottom: 16,
    marginHorizontal: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  image: {
    width: '100%',
    height: 200,
    borderTopLeftRadius: 8,
    borderTopRightRadius: 8,
  },
  content: {
    padding: 16,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 8,
    color: '#333',
  },
  summary: {
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
    marginBottom: 12,
  },
  date: {
    fontSize: 12,
    color: '#999',
  },
});

export default NewsCard;

五、总结

通过本章学习,我们掌握了React Native在鸿蒙平台上的基础组件使用和Flex布局适配。核心要点

  1. 组件基础:View、Text、Image是构建界面的三大核心组件
  2. 布局适配:鸿蒙平台Flex布局存在差异,建议使用绝对单位替代百分比
  3. 样式系统:使用StyleSheet.create提升性能,注意单位换算
  4. 最佳实践:采用响应式设计,针对不同设备尺寸做适配

避坑指南

  • 避免在低版本鸿蒙上使用justifyContent: 'space-between'
  • 图片加载使用onLoadonError处理加载状态
  • 复杂列表使用FlatListHarmonyList替代ScrollView

下一章我们将深入讲解状态管理与数据流,学习如何在React Native中管理应用状态和数据通信。

相关推荐
用户47949283569153 小时前
CVE-2025-55182:React 史上最严重漏洞,CVSS 满分 10.0
安全·react.js·全栈
盐焗西兰花4 小时前
鸿蒙学习实战之路-多端交互最佳实践
学习·交互·harmonyos
CnLiang4 小时前
React Compiler Plugin
前端·react.js
一只爱吃糖的小羊4 小时前
React 19 生命周期:从入门到实战的完整指南
前端·react.js
90后的晨仔5 小时前
鸿蒙开发必备:macOS 上 ohpm 的完整安装与配置指南(从报错到成功)
harmonyos
一只爱吃糖的小羊5 小时前
React 19:革命性升级与全面使用指南
react.js
一只爱吃糖的小羊5 小时前
React 19 vs Vue 3:深度对比与选型指南
前端·vue.js·react.js
光影少年5 小时前
react怎么实现响应式?
前端·react.js·前端框架
90后的晨仔6 小时前
安装ohpm报错ERROROR: node: command not found Failed to find the executable 'node'
harmonyos