发布于 2026-01-06 0 阅读
0

React Native 新手速查表

React Native 新手速查表

React Native 是由 Meta(Facebook 旗下公司)开发的跨平台框架,是目前最热门的移动应用开发框架之一。它遵循“一次学习,到处编写”的理念,允许用户使用 JavaScript、HTML5 和 CSS 文件创建组件。

React Native重新定义了原生应用的功能,解决了原生应用效率低下、部署缓慢的问题。它创建了兼具原生功能的混合应用。React Native基于React.js UI库,这使得Web开发者和移动应用开发者之间的切换更加便捷。

本文为 React Native 开发人员提供了一个简短的速查表,以方便开发过程。

入门

目录

  • 创建应用程序
  • 运行应用程序
  • 升级 React Native
  • 代码片段
  • 成分
  • 州和道具
  • useState 和 useEffect
  • 核心组件
  • 看法
  • ScrollView
  • 文本
  • 图像
  • 按钮
  • 可触摸高亮/可触摸不透明度
  • 文本输入
  • FlatList
  • 样式表
  • 内联样式
  • Flexbox
  • 检测屏幕尺寸
  • 导航
  • 使用导航钩子
  • 安卓 BackHandler
  • 联网
  • 创建示例应用程序
  • React Native 速查表 让我们来看看 React Native 的一些关键点。

创建应用程序

要创建一个新的移动应用,请打开终端并执行以下命令:

npx react-native init AppName
//or
npx create-react-native-app AppName
Enter fullscreen mode Exit fullscreen mode

运行应用程序

要运行该应用程序,请打开终端并执行以下命令:

cd AppName
npx react-native run-android
//or
npx react-native run-android
Enter fullscreen mode Exit fullscreen mode

升级 React Native

要将 React Native 升级到最新版本,请打开终端并执行以下命令:

npm install react-native@latest;
Enter fullscreen mode Exit fullscreen mode

代码片段

让我们来看一些在 React Native 项目中常用的代码片段。

成分

组件是轻量级模块,被视为 React 和 React Native 应用的核心构建块。App 组件是默认组件,它与 React Native 中的虚拟 DOM 绑定。React Native 中的每个组件都具有以下结构(View 和 Text 组件是可选的)。

import * as React from 'react';
import {View, Text, StyleSheet} from 'react-native'

const App = () => {
    return (
        <View style={styles.container}>
            <Text>Hello World</Text>
        </View>
    )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

州和道具

State 是一个可变存储,用于保存应用程序的整个状态树。Props
是一个不可变的 React Native 对象,由父组件设置,并且在组件的整个生命周期内保持不变。

import { useState } from "react";
import {
  StyleSheet,
  Text,
  View
} from 'react-native';

export default App = (props) => {
  const [count, setCount] = useState(0);

  return (
    <View >
      <Text style={styles.header}>
        {props.title?.toUpperCase()}
      </Text>
      <Text>Count: {count}</Text>
    </View>
  );
}

App.defaultProps = {
  title: 'Hello React Native'
}

const styles = StyleSheet.create({
  header: {
    fontFamily: 'Roboto',
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});
Enter fullscreen mode Exit fullscreen mode

useState 和 useEffect

useState hook 允许跟踪函数组件中的状态。useEffect
hook 允许用户执行诸如获取数据、直接更新 DOM 和在应用程序中使用定时器等副作用。

import { useState, useEffect } from "react";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  });

  return <h1>Count: {count}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

核心组件

核心组件是 React Native 中可直接使用的组件,包括 、 、 、FlatList 和 。

看法

<View>组件充当容器,并且可以<div>从 Web 翻译。

function App() {
  return (
    {/* Base layout structure */}
    <View style={{ flex: 1 }}>
      {/* Simple background color */}
      <View style={{ padding: 10, color: 'blue' }}>
        <Text>Text with background color</Text>
      </View>
      {/* Space layout structure */}
      <View style={{ margin: 10 }} />
    </View>
  );
}
Enter fullscreen mode Exit fullscreen mode

ScrollView

与类似View,它是一个具有滚动支持的通用容器,可为不同设备提供响应式布局。

function App() {
  return (
    <ScrollView>
      <Text style={{ margin: 10 }}>Hello World</Text>
      <View style={{ marginTop: 512 }} />
      <Text style={{ margin: 10 }}>Welcome to React Native</Text>
    </ScrollView>
  );
}
Enter fullscreen mode Exit fullscreen mode

文本

<Text>组件用于在 React Native 中显示文本。

function App() {
  return (
    <Text style={{ height: 20, margin: 10 }}>
      Hello World
    </Text>
  );
}
Enter fullscreen mode Exit fullscreen mode

图像

<Image>组件用于在 React Native 中渲染图像。它接受来自远程和本地的图像源。

function App() {
  return (
    <>
      <Image source={require('./assets/logo.jpg')} />
      <Image source={{ uri: 'https://github.com/codemaker2015/codemaker2015/raw/main/codemaker.png' }} />
      <Image source={{ uri: 'data:image/png;base64,<base64-string>=' }} />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

按钮

<Button>组件是一个可触摸元素,用于与屏幕交互并执行操作。

function App() {
  return (
    <Button
      onPress={onPressSubmit}
      title="Submit"
      color="#FFFFFF"
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

可触摸高亮/可触摸不透明度

<TouchableHighlight>`/`组件<TouchableOpacity>是一个用于使视图响应触摸事件的包装器。按下时,被包装视图的不透明度会降低,从而显示底层颜色。它必须至少有一个子组件。

import React, {useState} from 'react';
import {Text, TouchableHighlight, TouchableOpacity, View} from 'react-native';

const App = () => {
  const [count, setCount] = useState(0);
  const onIncrement = () => setCount(count + 1);
  const onDecrement = () => setCount(count - 1);

  return (
    <View
      style={{
        flex: 1,
        margin: 20,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Text>Count: {count}</Text>
      <TouchableOpacity
        onPress={onIncrement}
        style={{backgroundColor: '#F3F3F3', margin: 20, padding: 20}}>
        <Text>+</Text>
      </TouchableOpacity>
      <TouchableHighlight
        onPress={onDecrement}
        style={{backgroundColor: '#F3F3F3', margin: 20, padding: 20}}>
        <Text>-</Text>
      </TouchableHighlight>
    </View>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

文本输入

<TextInput>组件允许用户在应用程序中输入文本。它有一个 onChangeText 事件,每次文本更改时都会触发该事件。

import React, {useState} from 'react';
import {Text, TextInput, View} from 'react-native';

const App = () => {
  const [text, setText] = useState('');
  return (
    <View style={{padding: 15}}>
      <TextInput
        style={{height: 50}}
        placeholder="Enter name"
        onChangeText={name => setText(name)}
        defaultValue={text}
      />
      <Text style={{padding: 10, fontSize: 30}}>{text}</Text>
    </View>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

FlatList

<FlatList>组件显示一个可滚动的项目列表。它只渲染当前屏幕上显示的元素。

FlatList 组件需要两个 props:datarenderItemdata是列表的来源,renderItem返回要渲染的格式化组件。

import React from 'react';
import {FlatList, Text, View} from 'react-native';

const App = () => {
  return (
    <View>
      <FlatList
        data={[
          {key: 'January'},
          {key: 'February'},
          {key: 'March'},
          {key: 'April'},
        ]}
        renderItem={({item}) => <Text>{item.key}</Text>}
      />
    </View>
  );
};
Enter fullscreen mode Exit fullscreen mode

样式表

<StyleSheet>是一个抽象层,它通过使用二维 JavaScript 对象来接受 CSS 样式规则,从而取代 CSS。

function App() {
  return (
    <>
      <Text style={styles.heading}>React Native</Text>
      <Text style={styles.message}>Hello World</Text>
    </>
  );
}

const styles = StyleSheet.create({
  heading: {
    fontSize: 16,
  },
  message: {
    fontSize: 11,
    textTransform: 'uppercase',
  },
});
Enter fullscreen mode Exit fullscreen mode

内联样式

React Native 允许用户使用双花括号 ( ) 在 HTML 元素中添加样式{{}}

function App() {
    const [color, setColor] = useState("red");
    return (
       <View>
         <Text style={{"border":`1px solid ${color}`}}>Color: {color}</Text>
       </View>
    );
}
Enter fullscreen mode Exit fullscreen mode

Flexbox

<Flexbox>组件用于布局组件的子组件。

import { View, Text, StyleSheet } from "react-native";

const App = () => {
  return (
    <View style={[styles.container, {
      // Try setting `flexDirection` to `"column"`.
      flexDirection: "column"
    }]}>
      <View style={{ flex: 1, backgroundColor: "red" }} />
      <View style={{ flex: 2, backgroundColor: "orange" }} />
      <View style={{ flex: 3, backgroundColor: "green" }} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
  }
});

export default App;
Enter fullscreen mode Exit fullscreen mode

检测屏幕尺寸

检测设备的屏幕尺寸对于改变应用程序的布局、文本大小和其他方面至关重要。

import { Dimensions } from 'react-native';

const { width, height } = Dimensions.get('window');

alert(Screen size: ${width}x${height});
Enter fullscreen mode Exit fullscreen mode

导航

React Navigation 的原生堆栈导航器提供了一种让你的应用在屏幕之间过渡并管理导航历史记录的方法。

在 react-navigation 库中,所有导航器方法都遵循类似这样的命名模式create<type>Navigator(),它返回一个具有 Navigator 和 Screen 属性的对象。

createNativeStackNavigator是一个返回包含两个属性的对象:Screen和的函数Navigator。NavigationContainer
是一个组件,用于管理导航树并包含导航状态。
要安装该库,请执行以下代码。

npm install @react-navigation/native-stack
Enter fullscreen mode Exit fullscreen mode

用法:
在下面的代码中,创建了一个主屏幕组件并将其绑定到堆栈导航器。

import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
    </View>
  );
}

const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

使用导航钩子

useNavigation钩子提供了对导航 API 的访问,可用于实现从一个屏幕到另一个屏幕的过渡。

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function App() {
  const navigation = useNavigation();

  return (
    <Button
      title="Back"
      onPress={() => {
        navigation.goBack();
      }}
    />
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

安卓 BackHandler

为了从代码中处理返回按钮操作,BackHandler API 可以帮助检测用于返回导航的硬件按钮按下事件,并为系统的返回操作注册事件监听器。

import {useEffect} from 'react';
import {BackHandler} from 'react-native';

function App() {
  useEffect(() => {
    const backAction = () => {
      console.log("back button pressed");
      return false; // back button is enabled
      return true;  // back button is disabled
    };

    // Register for hardware back event and attach a handler to it
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );

    return () => backHandler.remove();
  }, []);
};

export default App;
Enter fullscreen mode Exit fullscreen mode

联网

大多数移动应用都需要从远程 URL 加载资源。React Native 提供了 Fetch API 用于从远程源获取数据。

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';

function App() {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  const getMovies = async () => {
     try {
      const response = await fetch('https://reactnative.dev/movies.json');
      const json = await response.json();
      setData(json.movies);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getMovies();
  }, []);

  return (
    <View style={{ flex: 1, padding: 20 }}>
      {isLoading ? <ActivityIndicator/> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text>{item.title}, {item.releaseYear}</Text>
          )}
        />
      )}
    </View>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

创建示例应用程序

让我们尝试创建一个个人资料组件,以便与 React Native 组件和其他功能进行交互。

  • 使用以下命令创建一个新的 React Native 项目
npx react-native init MyProfileApp
Enter fullscreen mode Exit fullscreen mode
  • 打开 App.js 文件,并将以下代码添加到其中。
import React, {useState, useEffect} from 'react';
import {
  Button,
  Image,
  StyleSheet,
  Text,
  View,
  ScrollView,
  Linking,
  Dimensions,
  ActivityIndicator,
} from 'react-native';

const {width, height} = Dimensions.get('window');

function Link(props) {
  return (
    <Text
      {...props}
      accessibilityRole="link"
      style={StyleSheet.compose(styles.link, props.style)}
    />
  );
}

function App() {
  const [logoUri, setLogoUri] = useState(
    'https://avatars.githubusercontent.com/',
  );
  const [loading, setLoading] = useState(false);

  const getLogoUri = async () => {
    try {
      setLoading(true);
      const response = await fetch(
        'https://api.github.com/users/codemaker2015',
      );
      const json = await response.json();
      setLogoUri(json?.avatar_url);
      setLoading(false);
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  };

  useEffect(() => {
    console.log('component is mounted');
    getLogoUri();
    return () => {
      console.log('component is unmounted');
    };
  }, []);

  return (
    <ScrollView contentContainerStyle={styles.app}>
      <View style={styles.header}>
        {loading ? (
          <ActivityIndicator />
        ) : (
          <Image
            accessibilityLabel="React logo"
            source={{uri: logoUri}}
            resizeMode="contain"
            style={styles.logo}
          />
        )}
        <Text style={styles.title}>Vishnu Sivan</Text>
      </View>
      <Text style={styles.subTitle}>Immersive tech lead, TCS RapidLabs</Text>
      <Text style={styles.text}>
        Seasoned professional, forward looking software engineer with 3+ years
        of experience in creating and executing innovative solutions in
        immersive field to enhance business productivity.
        {'\n\n'}
        <Link
          href="https://github.com/necolas/react-native-web"
          onPress={() => {
            Linking.openURL('https://github.com/codemaker2015');
          }}>
          Know more about me
        </Link>
      </Text>
      <Button
        onPress={() => {
          Linking.openURL('mailto:codemaker2015@gmail.com');
        }}
        title="Contact Me"
      />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  app: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F3F3F3',
    width: width,
    height: height,
  },
  logo: {
    width: 180,
    height: 180,
    borderRadius: 10,
  },
  header: {
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 10,
  },
  title: {
    fontWeight: 'bold',
    fontSize: 30,
    marginVertical: 10,
    textAlign: 'center',
  },
  subTitle: {
    fontWeight: 'bold',
    fontSize: 20,
    marginVertical: 10,
    textAlign: 'center',
  },
  text: {
    lineHeight: 20,
    fontSize: 18,
    margin: 18,
    textAlign: 'center',
  },
  link: {
    color: '#1B95E0',
  },
});
export default App;
Enter fullscreen mode Exit fullscreen mode
  • 执行以下命令运行应用程序
npx react-native run-android
Enter fullscreen mode Exit fullscreen mode

运行成功后,您可以看到以下页面。

演示

瞧!你的专属个人资料应用就用 React Native 做成了 :)

React Native 速查表

速查表

感谢阅读本文。

感谢 Gowri M Bhatt 对内容的审阅。

如果您喜欢这篇文章,请点击爱心按钮♥并分享,帮助更多人看到它!

本教程的完整源代码可以在这里找到,

GitHub - codemaker2015/react-native-cheatsheet

本文也可在Medium上阅读。

以下是一些实用链接,

文章来源:https://dev.to/codemaker2015/react-native-cheatsheet-for-beginners-28oa