Skip to content

基础API

从本章开始我们进入 RN 中一些 API 的学习。这里我将整个 RNAPI 分为了 5 个部分,分别是:

本小节我们先来看一下一些比较基础的 API,包含以下内容:

Alert#

Alert 主要用于显示一个带有指定标题和消息的警报对话框。Alert.alert 方法接收 3 个参数,一个参数是警报对话框的标题,第二个参数是警报内容,最后一个参数是一个数组,数组的每一项是按钮对象。

import React, { useState } from 'react'
import { View, StyleSheet, Button, Alert } from 'react-native'
const App = () => {
const createTwoButtonAlert = () =>
Alert.alert('Alert Title', 'My Alert Msg', [
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{ text: 'OK', onPress: () => console.log('OK Pressed') },
])
const createThreeButtonAlert = () =>
Alert.alert('Alert Title', 'My Alert Msg', [
{
text: 'Ask me later',
onPress: () => console.log('Ask me later pressed'),
},
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{ text: 'OK', onPress: () => console.log('OK Pressed') },
])
return (
<View style={styles.container}>
<Button title={'2-Button Alert'} onPress={createTwoButtonAlert} />
<Button title={'3-Button Alert'} onPress={createThreeButtonAlert} />
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
},
})
export default App

官方 API 文档:https://reactnative.dev/docs/alert

StyleSheet#

这个 API 我们在前面已经用过很多次了,StyleSheet 是一种类似于 CSS StyleSheets 的抽象。

需要注意以下几个点:

属性:

var styles = StyleSheet.create({
separator: {
borderBottomColor: '#bbb',
borderBottomWidth: StyleSheet.hairlineWidth,
},
})
const styles = StyleSheet.create({
wrapper: {
...StyleSheet.absoluteFill,
top: 10,
backgroundColor: 'transparent',
},
})

相当于以下代码的缩写:

position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0

方法:

var styles = StyleSheet.create({
listItem: {
flex: 1,
fontSize: 16,
color: 'white',
},
selectedListItem: {
color: 'green',
},
})
console.log(StyleSheet.flatten([styles.listItem, styles.selectedListItem]))
// returns { flex: 1, fontSize: 16, color: 'green' }

Transforms#

Transforms 类似于 CSS 中的变形。可以帮助我们使用 2D 或者 3D 变换来修改组件的外观和位置。

但是需要注意的是,一旦应用了变换,变换后的组件周围的布局将保持不变,因此它可能会与附近的组件重叠。

import React from 'react'
import { SafeAreaView, ScrollView, StyleSheet, Text, View } from 'react-native'
const App = () => (
<SafeAreaView style={styles.container}>
<ScrollView contentContainerStyle={styles.scrollContentContainer}>
<View style={styles.box}>
<Text style={styles.text}>Original Object</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ scale: 2 }],
},
]}
>
<Text style={styles.text}>Scale by 2</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ scaleX: 2 }],
},
]}
>
<Text style={styles.text}>ScaleX by 2</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ scaleY: 2 }],
},
]}
>
<Text style={styles.text}>ScaleY by 2</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ rotate: '45deg' }],
},
]}
>
<Text style={styles.text}>Rotate by 45 deg</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ rotateX: '45deg' }, { rotateZ: '45deg' }],
},
]}
>
<Text style={styles.text}>Rotate X&Z by 45 deg</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ rotateY: '45deg' }, { rotateZ: '45deg' }],
},
]}
>
<Text style={styles.text}>Rotate Y&Z by 45 deg</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ skewX: '45deg' }],
},
]}
>
<Text style={styles.text}>SkewX by 45 deg</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ skewY: '45deg' }],
},
]}
>
<Text style={styles.text}>SkewY by 45 deg</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ skewX: '30deg' }, { skewY: '30deg' }],
},
]}
>
<Text style={styles.text}>Skew X&Y by 30 deg</Text>
</View>
<View
style={[
styles.box,
{
transform: [{ translateX: -50 }],
},
]}
>
<Text style={styles.text}>TranslateX by -50 </Text>
</View>
<View
style={[
styles.box,
{
transform: [{ translateY: 50 }],
},
]}
>
<Text style={styles.text}>TranslateY by 50 </Text>
</View>
</ScrollView>
</SafeAreaView>
)
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollContentContainer: {
alignItems: 'center',
paddingBottom: 60,
},
box: {
height: 100,
width: 100,
borderRadius: 5,
marginVertical: 40,
backgroundColor: '#61dafb',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 14,
fontWeight: 'bold',
margin: 8,
color: '#000',
textAlign: 'center',
},
})
export default App

Keyboard#

Keyboard 模块用来控制键盘相关的事件。

利用 Keyboard 模块,可以监听原生键盘事件以做出相应回应,比如收回键盘。

import React, { useState, useEffect } from 'react'
import { Keyboard, Text, TextInput, StyleSheet, View } from 'react-native'
const Example = () => {
const [keyboardStatus, setKeyboardStatus] = useState(undefined)
useEffect(() => {
const showSubscription = Keyboard.addListener('keyboardDidShow', () => {
setKeyboardStatus('Keyboard Shown')
})
const hideSubscription = Keyboard.addListener('keyboardDidHide', () => {
setKeyboardStatus('Keyboard Hidden')
})
return () => {
showSubscription.remove()
hideSubscription.remove()
}
}, [])
return (
<View style={style.container}>
<TextInput
style={style.input}
placeholder="Click here…"
onSubmitEditing={Keyboard.dismiss}
/>
<Text style={style.status}>{keyboardStatus}</Text>
</View>
)
}
const style = StyleSheet.create({
container: {
flex: 1,
padding: 36,
},
input: {
padding: 10,
borderWidth: 0.5,
borderRadius: 4,
},
status: {
padding: 10,
textAlign: 'center',
},
})
export default Example

AppState#

RN 开发中,经常会遇到前后台切换的场景。为了监控应用的运行状态,RN 提供了 AppState。通过 AppState 开发者可以很容易地获取应用当前的状态。

AppState 中,应用的状态被分为:

要获取当前的状态,你可以使用 AppState.currentState,这个变量会一直保持更新。不过在启动的过程中,currentState 可能为 null,直到 AppState 从原生代码得到通知为止。

import React, { useRef, useState, useEffect } from 'react'
import { AppState, StyleSheet, Text, View } from 'react-native'
const AppStateExample = () => {
const appState = useRef(AppState.currentState)
const [appStateVisible, setAppStateVisible] = useState(appState.current)
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === 'active'
) {
console.log('App has come to the foreground!')
}
appState.current = nextAppState
setAppStateVisible(appState.current)
console.log('AppState', appState.current)
})
return () => {
subscription.remove()
}
}, [])
return (
<View style={styles.container}>
<Text>Current state is: {appStateVisible}</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
})
export default AppStateExample