React Native 之组件的导出
发布时间:2020-12-15 07:25:47 所属栏目:百科 来源:网络整理
导读:一:module.exports与exports 的区别 RN 首先组件的导出有两种方式 module.exports与exports 前者是ES5 写法 后者是ES6 写法,所以如果用ES5 导出一定要保持用ES5方式的引用方法 不然会报错的 因为 module.exports 初始值为一个空对象 {} exports 是指向的 m
一:module.exports与exports 的区别 RN 首先组件的导出有两种方式 module.exports与exports 前者是ES5 写法 后者是ES6 写法,所以如果用ES5 导出一定要保持用ES5方式的引用方法 不然会报错的 因为
所以如果用 module.exports 导出组件 在其它组件引用时候用 require 如: loginView.js 文件 class loginView extends Component {
render() {
return (
<View style={styles.container}>
.....
</View>
);
}
}
// 输出类
module.exports = loginView;
在index.android.js中 引用如下 import React,{ Component } from 'react';
import {
AppRegistry,StyleSheet,Text,View
} from 'react-native';
// 引入外部的js文件
let LoginView = require('./loginView');
class BTextInputDemo extends Component {
render() {
return (
<LoginView />
);
}
}
AppRegistry.registerComponent('BTextInputDemo',() => BTextInputDemo);
ES6 的写法 loginView
import React,{ Component } from 'react';
import {
AppRegistry,View
} from 'react-native';
export default class loginView extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React 123!
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},welcome: {
fontSize: 20,textAlign: 'center',margin: 10,}
});
index.android.js 文件 import React,View
} from 'react-native';
import LoginView from "./loginView";
export default class CQQLoginDemo extends Component {
render() {
return (
<LoginView/>
);
}
}
AppRegistry.registerComponent('CQQLoginDemo',() => CQQLoginDemo);
二:export 与 export default 的区别 export 可以在单个js文件中 导出多个组件 例如: export class Template{}
export class AnotherTemplate{}
这样在其他文件引用时,需要使用{}符号且组件名称必修和class名称一样,像这样子: import {Template,AnotherTemplate} from './components/Templates';
而加default时,例如: export default class Template{}
然后在其他文件引用,像这样子: import Template from './components/Templates';
你也可以为这个组件另起一个别名,像这样子: import TheTemplate from './components/Templates';
但是每个文件里只能有一个default组件,可以包含其他非default组件: export default class Template{}
export class AnotherTemplate{}
然后引用的时候,如下: import Template,{AnotherTemplate} from './components/Templates'; 主意:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |