如何在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
相关产品推荐
相关产品推荐

