react native 如何写组件
React Native 组件开发指南
React Native 组件开发主要分为两种类型:函数组件和类组件。以下分别介绍两种组件的写法及核心概念。
函数组件写法
函数组件是 React Native 推荐的方式,使用 Hooks 实现状态管理和生命周期。
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
const MyFunctionalComponent = ({ initialValue }) => {
const [count, setCount] = useState(initialValue || 0);
useEffect(() => {
console.log('Component mounted or count updated');
return () => {
console.log('Component will unmount');
};
}, [count]);
return (
<View style={styles.container}>
<Text>Count: {count}</Text>
<Button
title="Increment"
onPress={() => setCount(count + 1)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
padding: 20,
alignItems: 'center'
}
});
export default MyFunctionalComponent;
类组件写法
类组件通过继承 React.Component 实现,适用于需要完整生命周期控制的场景。
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
class MyClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: props.initialValue || 0
};
}
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return (
<View style={styles.container}>
<Text>Count: {this.state.count}</Text>
<Button
title="Increment"
onPress={() => this.setState({ count: this.state.count + 1 })}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
padding: 20,
alignItems: 'center'
}
});
export default MyClassComponent;
组件核心特性
Props(属性)
通过父组件传递数据,组件内通过 props(函数组件)或 this.props(类组件)访问。

State(状态)
组件内部可变数据,函数组件用 useState,类组件用 this.state 和 this.setState。
生命周期
函数组件通过 useEffect 模拟,类组件直接使用 componentDidMount 等方法。

样式处理
使用 StyleSheet.create 定义样式对象,支持 Flexbox 布局:
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
},
text: {
fontSize: 16,
color: '#333'
}
});
组件复用模式
高阶组件(HOC)
包装现有组件扩展功能:
const withLogger = (WrappedComponent) => {
return (props) => {
useEffect(() => {
console.log('Component rendered');
}, []);
return <WrappedComponent {...props} />;
};
};
自定义Hooks
封装可复用的逻辑:
const useCounter = (initialValue) => {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return { count, increment };
};
最佳实践
- 优先使用函数组件和 Hooks
- 复杂组件拆分为多个子组件
- 样式与逻辑分离,避免内联样式
- 使用
PropTypes或 TypeScript 定义 props 类型






