简单组件
import React from 'react'import { Text, View } from 'react-native';const App = () => {return (<View><Text>Hello, world!</Text></View>);}export default App;
定义Style
import React from 'react'import { Text, View } from 'react-native';const App = () => {return (<View style={{flex: 1,justifyContent: "center",alignItems: "center"}}><Text>Hello, world!</Text></View>);}export default App;
import React from 'react'import { Text, View, StyleSheet } from 'react-native';const styles = StyleSheet.create({center: {flex: 1,justifyContent: "center",alignItems: "center"}})const App = () => {return (<View style={styles.center}><Text>Hello, world!</Text></View>);}export default App;
自定义组件及Props
import React from 'react'import { Text, View, StyleSheet } from 'react-native';const styles = StyleSheet.create({center: {flex: 1,justifyContent: "center",alignItems: "center"},Greeting: {alignItems: "center",marginTop: 50,marginBottom: 50,}})const Greeting = (props: any) => {return (<View style={styles.Greeting}><Text>Hello {props.name}!</Text></View>);}const App = () => {return (<View style={[styles.center, {top: 10}]}><Greeting name='David' /><Greeting name='刘德华' /><Greeting name='盖尔·加朵' /></View>);}export default App;
State
import React, { useState } from 'react'import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';const styles = StyleSheet.create({container: {flex: 1,justifyContent: 'center',alignItems: 'center',},button: {alignItems: 'center',backgroundColor: '#DDDDDD',padding: 10,marginBottom: 10},redFont: {color: '#ff0000',fontSize: 20,}})const App = () => {const [count, setCount] = useState(0)const onPress = () => {setCount(count + 1)}return (<View style={styles.container}><TouchableOpacitystyle={styles.button}onPress={onPress}><Text>Click me</Text></TouchableOpacity><View><Text style={styles.redFont}>You clicked { count } times</Text></View></View>);}export default App;
自定义独立组件
LotsOfStyles.tsx
import React from 'react';import { StyleSheet, Text, View } from 'react-native';const LotsOfStylesList = () => {return (<View style={styles.container}><Text style={styles.red}>just red</Text><Text style={styles.bigBlue}>just bigBlue</Text><Text style={[styles.bigBlue, styles.red]}>bigBlue, then red</Text><Text style={[styles.red, styles.bigBlue]}>red, then bigBlue</Text></View>);};const styles = StyleSheet.create({container: {marginTop: 50,},bigBlue: {color: 'blue',fontWeight: 'bold',fontSize: 30,},red: {color: 'red',},});export default LotsOfStylesList;
app.tsx
import React from 'react'import { View } from 'react-native';import LotsOfStylesList from './LotsOfStyles';const App = () => {return (<View><LotsOfStylesList /></View>);}export default App;
