You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native函数组件中声明并使用普通类(非类组件)

在React Native函数组件中使用普通类实现计数功能

实现思路

创建独立的ES6普通类封装计数状态与逻辑,通过回调函数将类内状态变化同步到React组件状态中,确保组件能响应更新并重新渲染。

代码实现

1. 定义普通计数类

class Counter {
  constructor(updateCallback) {
    this.count = 0;
    this.updateCallback = updateCallback;
  }

  increaseCount() {
    this.count += 1;
    this.updateCallback(this.count);
  }

  getCount() {
    return this.count;
  }
}

2. 在函数组件中使用该类

import { useState, useRef, useEffect } from 'react';
import { View, Pressable, Text } from 'react-native';

const App = () => {
  const [displayCount, setDisplayCount] = useState(0);
  const counterRef = useRef(null);

  useEffect(() => {
    counterRef.current = new Counter((newCount) => {
      setDisplayCount(newCount);
    });
  }, []);

  return (
    <View style={{ padding: 20, marginTop: 50 }}>
      <Pressable 
        onPress={() => counterRef.current.increaseCount()}
        style={{ padding: 10, backgroundColor: '#eee', borderRadius: 5 }}
      >
        <Text>Increase</Text>
      </Pressable>
      <Text style={{ marginTop: 10, fontSize: 18 }}>{displayCount}</Text>
    </View>
  );
};

export default App;

关键说明

  • 普通类的作用:Counter类独立管理计数状态和递增逻辑,与React组件解耦,可复用在其他场景。
  • 状态同步机制:类通过构造函数接收的updateCallback,在increaseCount方法中触发组件的setDisplayCount,让React感知状态变化并重新渲染。
  • 实例持久化:用useRef保存Counter实例,避免组件每次渲染时重新创建实例,保证状态的连续性。

内容的提问来源于stack exchange,提问作者Harsh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:45:32