1、组件的导入导出方式
问1:如何导出一个组件?
export default class EIComponent extends Component{ render(){ return( <Text style = {{fontSize:20,backgroundColor:‘red‘}}>hello.</Text> ); } }
问2:如何在其他组件中使用导出的组件?
import HelloComponent from ‘./HelloComponent‘;
2、导出一个或多个变量
问1:如何导出一个或多个变量?
export var name = ‘小明‘; export var age = ‘22‘; // export {name,age};
问2:如何使用导出变量?
import HelloComponent,{name,age} from ‘./HelloComponent‘;
3、导入导出方法
问1:如何导出方法?
export function sum(a,b){ return a + b; }
问2:如何使用导出的方法?
import HelloComponent,{name,age,sum} from ‘./HelloComponent‘;
实例代码:
导出组件、变量、方法
import React, {Component} from ‘react‘; import {Platform, StyleSheet, Text, View} from ‘react-native‘; export var name = ‘小明‘; export var age = ‘22‘; // export {name,age}; export default class EIComponent extends Component{ render(){ return( <Text style = {{fontSize:20,backgroundColor:‘red‘}}>hello.</Text> ); } } export function sum(a,b){ return a + b; }
使用导出的组件、变量、方法
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow * @lint-ignore-every XPLATJSCOPYRIGHT1 */ import React, {Component} from ‘react‘; import {Platform, StyleSheet, Text, View} from ‘react-native‘; import HelloComponent,{name,age,sum} from ‘./HelloComponent‘; const instructions = Platform.select({ ios: ‘Press Cmd+R to reload,\n‘ + ‘Cmd+D or shake for dev menu‘, android: ‘Double tap R on your keyboard to reload,\n‘ + ‘Shake or press menu button for dev menu‘, }); type Props = {}; export default class App extends Component<Props> { constructor(props){ super(props); this.state =({ result:‘‘ }) } render() { return ( <View style={styles.container}> <Text style ={styles.welcome}>名字:{name}</Text> <Text style ={styles.welcome}>年龄:{age}</Text> <Text style ={styles.welcome} onPress={()=>{ var result = sum(2,3); this.setState({ result:result }) }} >2+3={this.state.result}</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: ‘center‘, alignItems: ‘center‘, backgroundColor: ‘white‘, }, welcome: { fontSize: 20, textAlign: ‘center‘, margin: 10, }, instructions: { textAlign: ‘center‘, color: ‘#333333‘, marginBottom: 5, }, });
原文地址:https://www.cnblogs.com/xjf125/p/10366268.html
时间: 2024-10-11 12:22:15