- 概述:
开发的过程中,有很多需要抽象出来可以拿来公用的模块,比如App的顶栏
本文就介绍一下ES6怎么写独立的模块的导出和导入。
- /**
- * Sample React Native App
- * https://github.com/facebook/react-native
- */
- import React,{
- AppRegistry,Component,StyleSheet,Text,PixelRatio,View,} from 'react-native';
- class Header extends Component {
- /*
- api自带渲染函数,重写该方法
- */
- render() {
- return (
- <View style={styles.flex}>
- <Text style= {styles.font}>
- <Text style = {styles.font_1}>
- 网易
- </Text>
- <Text style = {styles.font_2}>
- 新闻
- </Text>
- <Text>
- 有态度°
- </Text>
- </Text>
- </View>
- );
- }
- }
- //定义样式
- const styles = StyleSheet.create({
- flex:{
- marginTop: 25,height: 50,borderBottomWidth: 3/React.PixelRatio.get(),borderBottomColor: "#EF2D36",alignItems: "center",},font:{
- fontSize: 25,fontWeight: "bold",textAlign: "center",font_1:{
- color: "#CD1D1C",font_2:{
- color: "#FFF",backgroundColor: "#CD1D1C",});
- /**
- * 导出该类作为独立的模块
- */
- export default class MyHeader extends Header {
- }
此处最关键的就是
MyHeader是自己创建的类名称,导入的时候用到,这里extends继承的就是Header类;
- /**
- * 导出该类作为独立的模块
- */
- export default class MyHeader extends Header {
- }
到这里自定义的类导出写法就完成了。
接下来是介绍怎么导入抽出来的类写法:
- /**
- * Sample React Native App
- * https://github.com/facebook/react-native
- */
- import React,} from 'react-native';
- // import MyComponent from './MyComponent.js';
- /**
- * 导入自己写好的header类
- */
- import MyHeader from './Header.js';
- class TestProject extends Component{
- /*
- api自带渲染函数,重写该方法
- */
- render() {
- return (
- <View style = {styles.flex}>
- <MyHeader></MyHeader>
- </View>
- );
- }
- }
- //定义样式
- const styles = StyleSheet.create({
- flex:{
- flex: 1,});
- //注册项目
- AppRegistry.registerComponent('TestProject',() => TestProject);
关键的就一句话:
到这里,就全部完成了独立抽象模块的导出和导入ES6写法。