在本教程中,了解在创建通用应用时如何处理原生和 Web 之间的平台差异。
Android、iOS 和 Web 具有不同的功能。在我们的例子中,Android 和 iOS 都可以使用 react-native-view-shot
库捕获屏幕截图,但是 Web 浏览器则不能。
¥Android, iOS, and the web have different capabilities. In our case, both Android and iOS can capture a screenshot with the react-native-view-shot
library, however, web browsers cannot.
在本章中,我们将学习如何为网络浏览器设置例外,以便在所有平台上获得相同的功能。
¥In this chapter, let's learn how to make an exception for web browsers to get the same functionality on all platforms.
1
¥Install and import dom-to-image
为了在网络上捕获屏幕截图并将其保存为图片,我们将使用名为 dom-to-image 的第三方库。它允许截取任何 DOM 节点的屏幕截图并将其转换为矢量 (SVG) 或光栅(PNG 或 JPEG)图片。
¥To capture a screenshot on the web and save it as an image , we'll use a third-party library called dom-to-image. It allows taking a screenshot of any DOM node and turning it into a vector (SVG) or raster (PNG or JPEG) image.
停止开发服务器并运行以下命令来安装库:
¥Stop the development server and run the following command to install the library:
-
npm install dom-to-image
安装完成后,请确保重新启动开发服务器并在终端中按 w。
¥After installing it, make sure to restart the development server and press w in the terminal.
要使用它,我们将其导入到 App.js 中:
¥To use it, let's import it into App.js:
import domtoimage from 'dom-to-image';
2
¥Add platform-specific code
React Native 提供了一个 Platform
模块,使我们能够访问有关应用当前运行的平台的信息。你可以使用它来实现特定于平台的行为。
¥React Native provides a Platform
module that gives us access to information about the platform on which the app is currently running.
You can use it to implement platform-specific behavior.
在 App.js 中导入 Platform
模块:
¥Import the Platform
module in App.js:
import { StyleSheet, View, Platform } from 'react-native';
在 <App>
组件的 onSaveImageAsync()
函数中,我们将使用 Platform.OS
来检查平台是否为 'web'
。如果不是 'web'
,我们将运行之前添加的逻辑来截取并保存屏幕截图。如果是 'web'
,我们将使用 domtoimage.toJpeg()
方法将当前的 <View>
转换并捕获为 JPEG 图片。
¥Inside the onSaveImageAsync()
function in the <App>
component, we'll use Platform.OS
to check whether the platform is 'web'
.
If it is not 'web'
, we'll run the logic added previously to take and save the screenshot. If it is 'web'
,
we'll use the domtoimage.toJpeg()
method to convert and capture the current <View>
as a JPEG image.
const onSaveImageAsync = async () => {
if (Platform.OS !== 'web') {
try {
const localUri = await captureRef(imageRef, {
height: 440,
quality: 1,
});
await MediaLibrary.saveToLibraryAsync(localUri);
if (localUri) {
alert('Saved!');
}
} catch (e) {
console.log(e);
}
} else {
try {
const dataUrl = await domtoimage.toJpeg(imageRef.current, {
quality: 0.95,
width: 320,
height: 440,
});
let link = document.createElement('a');
link.download = 'sticker-smash.jpeg';
link.href = dataUrl;
link.click();
} catch (e) {
console.log(e);
}
}
};
在网络浏览器中运行应用时,我们现在可以保存屏幕截图:
¥On running the app in a web browser, we can now save a screenshot:
¥Next step
该应用完成了我们为其设定的所有功能,因此是时候将我们的注意力转向纯粹的美学了。
¥The app does everything we set out for it to do, so it's time to shift our focus toward the purely aesthetic.
在下一章中,我们将自定义应用的状态栏、启动画面和应用图标。