ES6 导出组件或属性 方式案例

来源:互联网 发布:复旦大学香港大学知乎 编辑:程序博客网 时间:2024/06/05 18:13

ES6 导出组件或属性

  • ES6 导出属性
    1. 匿名方式
// 定义:匿名对象存放所需要的属性// CommonData.jsexport default{    title:"cralos",    age:20,}
//引用:引用匿名对象//test.js //此处的Data可以定义任意名称来指向CommonData.jsimport Data from "./CommonData.js"console.log(Data.title);
  1. 固定方式
// 定义:定义一个常量对象存放所需要的属性// CommonData.jsexport const CommData={    title:"cralos",    age:20,}
//引用:引用固定对象//test.js //此处的CommData必须和CommonData.js定义的保持一致,并且加大括号import {CommData} from "./CommonData.js"console.log(Data.title);
  • ES6 导出组件
//引入属性类型import PropTypes from 'prop-types';eg: 常见类型width: PropTypes.number,onPress: PropTypes.func,containerStyle: PropTypes.any,source: Image.propTypes.source,rounded: PropTypes.bool,title: PropTypes.string,//属性的任意一个类型component: PropTypes.oneOf([    View,    TouchableOpacity,    TouchableHighlight,    TouchableNativeFeedback,    TouchableWithoutFeedback, ]),

1、const 类型

const CommonComponent=props=>{    //1、定义属性    const{        title,        titleStyle,        onPress,        ...attributes    }=props;    //2、定义属性的类型限制    CommonComponent.propTypes={        title:PropTypes.string,        titleStyle:Text.propTypes.style,        onPress:PropTypes.func,    }    //3.1、返回组件视图    return(        <View>            {renderContent()}        </View>    );    //3.2、渲染视图    const renderContent=()=>{    if(title){     return(            <Text            onPress={onPress}            style={[styles.title,titleStyle && titleStyle]}            > {title}</Text>        );       }    //4、定义视图的样式    const styles = StyleSheet.create({        title:{fonsize:13}    })};//5、导出该组件export default CommonComponent;
  1. 组件类型
import React, { Component } from 'react';import { Text } from 'react-native';class HelloWorldComponent extends Component {  render() {    return (      <Text>Hello world!</Text>    );  }}export HelloWorldComponent
原创粉丝点击