react-native(expo)项目中如何实现手电筒开关切换功能?
react-native-torch依赖原生配置修改,无法在标准Expo项目中运行,你可以通过以下两种Expo官方支持的方式实现手电筒控制:
方案1:使用Expo Camera组件的常亮模式
你之前了解的flashMode属性不止支持拍照时闪光,它还有torch常量可以直接让闪光灯常亮作为手电筒使用,不需要触发拍照动作,实现步骤如下:
- 先安装expo-camera依赖,申请相机权限
- 组件中引入
Camera以及FlashMode枚举 - 通过状态控制
flashMode的值在FlashMode.off和FlashMode.torch之间切换即可实现手电筒开关
示例代码:
import { Camera, FlashMode } from 'expo-camera'; import { useState, useEffect } from 'react'; import { Button, View, Text } from 'react-native'; export default function TorchController() { const [hasPermission, setHasPermission] = useState(null); const [isTorchOn, setIsTorchOn] = useState(false); useEffect(() => { (async () => { const { status } = await Camera.requestCameraPermissionsAsync(); setHasPermission(status === 'granted'); })(); }, []); if (hasPermission === null) return <View />; if (hasPermission === false) return <Text>无相机权限无法使用手电筒</Text>; return ( <View style={{ flex: 1 }}> {/* 隐藏相机预览组件,不影响原有页面布局 */} <Camera style={{ width: 1, height: 1, opacity: 0 }} flashMode={isTorchOn ? FlashMode.torch : FlashMode.off} /> <Button title={isTorchOn ? "关闭手电筒" : "打开手电筒"} onPress={() => setIsTorchOn(!isTorchOn)} /> </View> ); }
方案2:使用独立手电筒模块(适用于SDK 46及以上版本)
如果不想引入Camera组件,可以使用独立的手电筒能力,实现更轻量,不需要挂载隐藏的相机组件:
- 安装对应的手电筒依赖后,申请相关权限
- 直接调用对应的开关接口即可控制
示例代码:
import * as Flashlight from 'expo-flashlight'; import { useState } from 'react'; import { Button, View, Alert } from 'react-native'; export default function TorchController() { const [isTorchOn, setIsTorchOn] = useState(false); const toggleTorch = async () => { try { const available = await Flashlight.isAvailableAsync(); if (!available) { Alert.alert("当前设备不支持手电筒功能"); return; } await Flashlight.toggleTorchAsync(!isTorchOn); setIsTorchOn(!isTorchOn); } catch (e) { Alert.alert("控制手电筒失败,请检查权限"); } }; return ( <View> <Button title={isTorchOn ? "关闭手电筒" : "打开手电筒"} onPress={toggleTorch} /> </View> ); }
内容的提问来源于stack exchange,提问作者A-wels
相关产品推荐
相关产品推荐

