ReactNative Expo 急速教程

6,950 阅读5分钟

笔记:

  1. segmentfault.com/a/119000002…
  2. docs.expo.io/

react-native 相信大部分前端开发都不会陌生——使用 JavaScript 和 React 编写原生移动应用。

面临的问题

使用RN编写应用,共有两种方式 expo-cli;一种是通过 create-react-native-app。其中的Expo方式的优势是,无需配置 iOS Android 编译环境,发布时,需要安装Expo来执行应用。

且expo 可以和纯 react-native 项目互转而不至于被绑定在某一个类型上。

准备环境

1、安装 expo-cli

npm install expo-cli --global

2、创建项目

expo init my-new-project

会有两类模板让你选择:托管工作流,裸露工作流:

expo init simple-project
? Choose a template:
  ----- Managed workflow -----
❯ blank                 a minimal app as clean as an empty canvas
  blank (TypeScript)    same as blank but with TypeScript configuration
  tabs                  several example screens and tabs using react-navigation
  ----- Bare workflow -----
  minimal               bare and minimal, just the essentials to get you started
  minimal (TypeScript)  same as minimal but with TypeScript configuration

3、启动项目

cd my-new-project
expo start

4、预览项目

项目启动后,有两种方式预览:在AppStore上下载 Expo Client 手机客户端,扫描二维码;或者 在终端w启动浏览器,输入 a 或 i,启动 Android 或 iOS 模拟器。

编写第一个应用

此应用默认显示一个图片,允许用户选择图片,并分享图片。

修改你的目录内的app.js:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
  return (
    <View style={styles.container}>
      <Text>To share a photo from your phone with a friend, just press the button below!</Text>
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

可以通过浏览器或者手机Expo预览,看到界面正中显示一个文字。

现在这个文字有点太小了,可以通过修改添加style来加大文字:

<Text style={{color: '#888', fontSize: 18}}> 

添加一个图片

我们使用React Native中的Text组件显示了文本,我们可以使用Image组件显示图像。在创建Image组件时,你需要明确指定宽度和高度,否则图像将不可见。

在文件导入中添加Image组件,并且通过import导入静态图片logo.png为对象logo:

import { Image,  StyleSheet, Text, View } from 'react-native';
import logo from './assets/logo.png'; 

可以在View组件内的第一行添加此组件,指定Source为logo对象:

<Image source={logo} style={{ width: 305, height: 159 }} /> 

编写完成后的文件如下:

import React from 'react';
import { Image,  StyleSheet, Text, View } from 'react-native';
import logo from './assets/logo.png'; 
export default function App() {
  return (
    <View style={styles.container}>
      <Image source={logo} style={{ width: 305, height: 159 }} /> 
      <Text style={{color: '#888', fontSize: 18}}> 
        To share a photo from your phone with a friend, just press the button below!
      </Text>
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

添加一个按钮

我们将使用TouchableOpacity组件和里面的一些样式化的Text来创建我们自己的自定义按钮。

首先导入此组件:

import { Image, StyleSheet, Text,  View,TouchableOpacity } from 'react-native';

在Image组件后添加此组件:

  <TouchableOpacity
        onPress={() => alert('Hello, world!')}
        style={{ backgroundColor: 'blue' }}>
        <Text style={{ fontSize: 20, color: '#fff' }}>Pick a photo</Text>
      </TouchableOpacity>

其中的TouchableOpacity属性onPress内可以直接挂接事件代码,此处就是显示一个alert。

编写后的代码:

import React from 'react';
import { Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
export default function App() {
  return (
    <View style={styles.container}>
      <Image source={{ uri: 'https://i.imgur.com/TkIrScD.png' }} style={styles.logo} />
      <Text style={styles.instructions}>
        To share a photo from your phone with a friend, just press the button below!
      </Text>
      <TouchableOpacity
        onPress={() => alert('Hello, world!')}
        style={{ backgroundColor: 'blue' }}>
        <Text style={{ fontSize: 20, color: '#fff' }}>Pick a photo</Text>
      </TouchableOpacity>
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  logo: {
    width: 305,
    height: 159,
    marginBottom: 20,
  },
  instructions: {
    color: '#888',
    fontSize: 18,
    marginHorizontal: 15,
    marginBottom: 10,
  },
});

选择一个图片

到目前为止,我们一直在应用中使用React和React Native的代码。React为我们提供了一种很好的构建组件的方式,而React Native则为我们提供了可以在iOS、Android和web上运行的预构建组件--比如View、Text、TouchableOpacity。React Native并没有为我们提供一个图片选取器。为此,我们可以使用一个名为expo-image-picker的Expo库。

首先需要安装此组件:

expo install expo-image-picker

导入组件,挂接事件处理函数,编写事件处理函数:

export default function App() {
  const [selectedImage, setSelectedImage] = React.useState(null);
  let openImagePickerAsync = async () => {
    let permissionResult = await ImagePicker.requestCameraRollPermissionsAsync();
    if (permissionResult.granted === false) {
      alert('Permission to access camera roll is required!');
      return;
    }
    let pickerResult = await ImagePicker.launchImageLibraryAsync();
    if (pickerResult.cancelled === true) {
      return;
    }
    setSelectedImage({ localUri: pickerResult.uri });
  };
  if (selectedImage !== null) {
    return (
      <View style={styles.container}>
        <Image
          source={{ uri: selectedImage.localUri }}
          style={styles.thumbnail}
        />
      </View>
    );
  }
  return (
    <View style={styles.container}>
      {/* Our logo, instructions, and picker button are hidden here to keep the example brief */}
    </View>
  );
}
const styles = StyleSheet.create({
  /* Other styles hidden to keep the example brief... */
  thumbnail: {
    width: 300,
    height: 300,
    resizeMode: "contain"
  }
});

其中的react.useState(0)是一个Hook,声明了一个状态变量selectedImage,获取方式是访问selectedImage,设置方式为setSelectedImage。

React钩子是一种新的方式,可以在不使用类的情况下访问react的核心功能,比如状态,在你的例子中,如果你想在处理函数中直接递增一个计数器,而不直接在onClick道具中指定它,你可以做这样的事情。

...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};

在事件onClick内:

<button onClick={setCount}>
    Click me
</button>

useState(0)的参数0表示状态对象的初始值,函数返回一个元组,其中第一个参数count是计数器的当前状态,setCounter是允许我们更新计数器状态的方法。我们可以在任何地方使用setCounter方法来更新count的状态--在这种情况下,我们是在setCount函数内部使用它,在那里我们可以做更多的事情;使用钩子的想法是,我们能够保持我们的代码有更多的功能,如果不希望/不需要,就避免基于类的组件。

总结

本文搭建了一个Expo的环境,并编写了一个简单的显示图片和处理事件的app,此app使用了RN内置组件和Expo组件。由此可以进入Expo开发的世界。