当前位置: > > > React Native - 将组件导出(exports)成独立模块(附使用样例)

React Native - 将组件导出(exports)成独立模块(附使用样例)

在项目开发中常常有一些功能组件在许多页面中都是可以复用的。本文演示如何将自定义组件导出成独立的模块,以及如何导入使用这个模块。

1,效果图

通常许多页面的头部是一样的。这里我们以封装一个公用的头部组件为例。
原文:React Native - 将组件导出(exports)成独立模块(附使用样例)


2,组件代码

我们把下面的组件代码放在 header.js 文件中,代码的最后我们将其 export 成独立的模块。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React, { Component } from 'react';
import {
 AppRegistry,
 StyleSheet,
 Text,
 View,
 PixelRatio,
} from 'react-native';
 
export default class Header extends Component {
   render() {
     return (
       <View style={styles.flex}>
         <Text style={styles.font}>hangge.com</Text>
       </View>
     );
   }
}
 
const styles = StyleSheet.create({
 flex:{
    marginTop:20,
    height:50,
    borderBottomWidth:3/PixelRatio.get(),
    borderBottomColor:'#2D9900',
    alignItems:'center', /*使Text组件水平居中*/
    justifyContent:'center' /*使Text组件垂直居中*/
 },
 font:{
    color:"#2D9900",
    fontSize:25,
    fontWeight:'bold',
    textAlign:'center' /*使文字在Text组件中居中*/
  },
});

3,使用样例

使用时我们通过 require 函数将 Header 组件加载进来即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React, { Component } from 'react';
import {
 AppRegistry,
 StyleSheet,
 Text,
 View,
} from 'react-native';
 
import Header from './header'
 
class Main extends Component {
   render() {
     return (
       <View style={styles.flex}>
         <Header></Header>
       </View>
     );
   }
 }
 
 const styles = StyleSheet.create({
  flex:{
     flex:1
  },
 });
 
 AppRegistry.registerComponent('HelloWorld', () => Main);
评论0