react native 如何写组件
创建 React Native 组件的基本方法
React Native 组件通常通过 JavaScript 或 TypeScript 编写,分为函数组件和类组件两种形式。以下是创建组件的核心步骤:
函数组件示例
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const MyComponent = ({ title }) => {
return (
<View style={styles.container}>
<Text style={styles.text}>{title}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
padding: 16,
backgroundColor: '#f5f5f5'
},
text: {
fontSize: 18,
fontWeight: 'bold'
}
});
export default MyComponent;
类组件写法
对于需要状态管理的复杂组件,可以使用类组件:
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class ClassComponent extends Component {
render() {
return (
<View style={styles.container}>
<Text>{this.props.title}</Text>
</View>
);
}
}
// 样式和导出同上
组件属性类型检查
使用 PropTypes 或 TypeScript 进行类型检查:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
title: PropTypes.string.isRequired
};
// TypeScript 接口写法
interface Props {
title: string;
}
状态管理
函数组件中使用 useState Hook:
const [count, setCount] = React.useState(0);
类组件中使用 this.state:
this.state = { count: 0 };
this.setState({ count: this.state.count + 1 });
生命周期管理
函数组件使用 useEffect Hook:
React.useEffect(() => {
console.log('组件挂载');
return () => console.log('组件卸载');
}, []);
类组件使用传统生命周期方法:
componentDidMount() {
console.log('组件挂载');
}
componentWillUnmount() {
console.log('组件卸载');
}
样式组织
推荐使用 StyleSheet 创建样式对象:
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
}
});
组件复用模式
高阶组件(HOC)示例:
function withLogger(WrappedComponent) {
return (props) => {
console.log('组件渲染:', props);
return <WrappedComponent {...props} />;
};
}
最佳实践建议
-
保持组件单一职责原则
-
将大型组件拆分为多个小组件
-
使用 memo 优化性能:
export default React.memo(MyComponent); -
为可交互组件添加 accessibility 属性
-
使用主题上下文统一样式管理







