RN | class 组件和函数式组件

class 组件

特点

  • 有状态(state),每次都是修改同一个状态
  • 基于生命周期管理
  • 面向对象
jsx 复制代码
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View} from 'react-native';

export class ClassView extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <View style={{width: 200, height: 200, backgroundColor: 'blue'}} />;
  }
}

生命周期

constructor->render->componentDidMount->componentWillUnmount(当组件即将从 DOM 中移除时会触发)

props 传递

jsx 复制代码
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Text, View} from 'react-native';

export class ClassView extends React.Component {
  constructor(props) {
    console.log('constructor...');
    super(props);
  }

  componentDidMount() {
    console.log('componentDidMount...');
  }

  componentWillUnmount() {
    console.log('componentWillUnmount...');
  }

  render() {
    console.log('render...');
    const {name, age, gender} = this.props;
    return (
      <View
        style={{
          width: '100%',
          height: 200,
          backgroundColor: 'blue',
        }}>
        <Text style={{color: '#fff'}}>{name}</Text>
        <Text style={{color: '#fff'}}>{age}</Text>
      </View>
    );
  }
}

class 组件内部的 state

jsx 复制代码
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Text, View} from 'react-native';

export class ClassView extends React.Component {
  constructor(props) {
    console.log('constructor...');
    super(props);
    this.state = {
      showDetail: true,
    };
  }

  componentDidMount() {
    console.log('componentDidMount...');

    // 5s后隐藏具体信息
    setTimeout(() => {
      this.setState({
        showDetail: false,
      });
    }, 5000);
  }

  render() {
    console.log('render...');
    const {name, age, gender} = this.props;
    return (
      <View
        style={{
          width: '100%',
          height: 200,
          backgroundColor: 'blue',
        }}>
        {this.state.showDetail && (
          <>
            <Text style={{color: '#fff'}}>{name}</Text>
            <Text style={{color: '#fff'}}>{age}</Text>
            <Text style={{color: '#fff'}}>{gender}</Text>
          </>
        )}
      </View>
    );
  }
}

函数式组件和hook

特点

  • 无状态,每次刷新都是生成一个新的状态
  • 基于状态变化的管理
  • 简洁,代码少,易于复用

hooks

  • useState
  • useRef
  • useWindowDimensions
  • useColorScheme

useWindowDimensions

useWindowDimensions 是一个用于获取设备窗口尺寸的 Hook,它会在窗口大小发生变化时自动更新。这对于响应式布局特别有用。

useWindowDimensions 返回一个对象,包含以下属性:

ts 复制代码
interface WindowDimensions {
  width: number;       // 窗口宽度
  height: number;      // 窗口高度
  scale: number;       // 设备像素比
  fontScale: number;   // 字体缩放比例
}

useColorScheme

用于获取用户设备当前的颜色主题偏好(深色或浅色模式)

useColorScheme() 返回值可能是:

  • 'light' - 浅色模式
  • 'dark' - 深色模式
  • null - 未知或不支持

PS:

  • 需要在 React Native 0.63 或更高版本中使用
  • iOS 13+ 和 Android 10+ 才能完全支持

例子:

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

function MyComponent() {
  const colorScheme = useColorScheme();
  
  return (
    <View style={{
      backgroundColor: colorScheme === 'dark' ? '#000' : '#fff',
      // ...
    }}>
      <Text style={{
        color: colorScheme === 'dark' ? '#fff' : '#000',
      }}>
        当前主题: {colorScheme}
      </Text>
    </View>
  );
}
相关推荐
Warren981 小时前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
mCell2 小时前
JavaScript 运行机制详解:再谈 Event Loop
前端·javascript·浏览器
独行soc5 小时前
2025年渗透测试面试题总结-18(题目+回答)
android·python·科技·面试·职场和发展·渗透测试
雨白5 小时前
登录和授权:Cookie与Authorization Header机制详解
android
帧栈6 小时前
开发避坑指南(27):Vue3中高效安全修改列表元素属性的方法
前端·vue.js
max5006006 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
excel6 小时前
使用函数式封装绘制科赫雪花(Koch Snowflake)
前端
Frank_HarmonyOS6 小时前
【Android -- 多线程】Handler 消息机制
android
萌萌哒草头将军7 小时前
Node.js v24.6.0 新功能速览 🚀🚀🚀
前端·javascript·node.js
一条上岸小咸鱼7 小时前
Kotlin 基本数据类型(一):概述及分类
android·kotlin